Bootstrap Validation States Dynamically

Tutorial showing how to use Bootstrap validation states dynamically. A wrong entry in a form produces an error message and appropriate styling.

Bootstrap Validation States Dynamically

Bootstrap includes validation styles for error, warning, and success states on form controls. Unfortunately the examples given are all static.

Plugins

While working on form validation I discovered the following plugins:

  1. Jquery Validation
  2. jqBootstrapValidation
  3. Validator
  4. BootstrapValidator

I decided to use BootstrapValidator because:

  • it already includes the Bootstrap validation states,
  • provides a lot of built-in validators,
  • features a solution for complex forms,
  • looks to be well maintained.
Free version of BootstrapValidator After writing this post the plugin was commercialised (under the name Formvalidation). However you can download the zipfile containing the older, free version on GitHub (which suffices for this tutorial) using the hyperlink above.
I will show you how to add validation to two forms (from previous tutorials):

  1. The Contact Modal
  2. The Form with script to insert data in a database

Before going into how to specifically add validation to these two forms I’ll explain how to link the plugin to a form:

How to add the BootstrapValidator plugin

The BootstrapValidator plugin provides both style rules and a script. So we need to add these first. In this tutorial I will use CDN links to the plugin files. We start with the link for the Validator stylesheet. Insert the link shown below in the head section; just after the link for the Bootstrap stylesheet:

We then add a CDN link for the plugin as well as the script to run BootstrapValidator. Insert the code below after the links for jQuery and the Bootstrap plugin(s):

Make sure that the ID your select in the script (e.g. ‘#IDofyourform’) is the same as the ID for your form.

I will now explain how to add the validation (states) to the Contact Modal. That will allow me to start with some simple validation examples.If you want to skip the Contact Modal section you can click this link to jump directly to jump directly to the Data Insert Form section of this tutorial.

The Contact Modal

The demo below shows The Contact Modal with the validation (states):

Demo Contact Modal - Validation States Dynamically

To see the error validation state work just open the Contact Modal in the demo and click on “Send”.

In this demo I only added the ‘required’ condition for the input fields “First Name”, “Last Name” and “Email”. Later on we’ll add other conditions.

The BootstrapValidator plugin provides 2 methods to validate a form: with data-attributes in the HTML or with a JavaScript. We’ll look at each of these 2 methods in turn. Starting with the HTML approach:

HTML method

With this method we set the validation using HTML 5 attributes prefixed with data-bv.

Tip! Keep your original HTML file and insert the code examples below in a copy!

To set a default error message (see line 2) we insert ‘data-bv-message=”your error message”‘ in the opening form tag.

Below that you can see how to include the validation icons (line 3-5).

To set an input field as ‘required’ we insert the attribute data-bv-notempty.

And to set a specific error message for this we include the attribute ‘data-bv-notempty-message=”your particular error message”‘.

JavaScript method

The alternative method to set validation for a form is with a script:

We start by including the default error message and the validation icons in the script.

After that we define the validators for each of the input fields. In the code example above I also made use of a validator provided by BootstrapValidator: emailAddress.

The last part of the script was included because our form resides inside a modal. Adding these two lines to the script will ensure that the form -inside a modal – is reset when a user closes and then re-opens the form.

Error messages in tooltips or popovers

With the BootstrapValidator plugin we can also display the validation messages in either a tooltip or a popover. Below you can see how to change the previously shown JavaScript to use the popover option:

I noticed a few styling issues when using the popover option. The popover itself is styled in a red hue but the arrow stays white. I found the popover rather narrow and noticed that the first popover was cut off at the top. To remedy this I added the following styling rules:

Below you can check out a demo of the validation with popovers:

Demo Contact Modal - Validation Messages inside Popovers

To see the error messages: click on the button “Open Contact Form”, click send and then hover over one of the error icons to see a popover.

Warning! In the tutorial about the Contact Modal I included an extra section about how to add a Thank You popover (see section titled 'Thank You Message' in the 'Bootstrap 3 Contact Modal' tutorial). Do not add that Thank You Message script since this can lead to strange effects in combination with the validation plugin.

The Data Insert Form

We’ll now turn to the validation of a more complex form: Form with script sending data to a database.

In the demo below you can see what the end result will look like:

Demo - Validation of Form to Send Data

To see the validation in action type in a number or symbol (e.g. #) in the input fields for First or Last Name; insert a text without a @ in the input field for email, or simply click on the ‘Submit’ button.

Below you can see the script used in the demo:

Most of the script will be familiar to you because it uses the same elements to set icons, input fields validation and messages, etc.

I’d like to draw your attention to two particular aspects of this script:

  1. The use of the group option. By default the validation is linked to the class form-group. In our “complex” form a form-group contains 2 input fields (e.g. both First Name and Last Name reside within one form-group). This would lead to strange validation effects. To remedy this issue you need to define a group for each input field. You can see that I’ve done this with group: '.col-sm-4' (in this particular form each input field has the same ‘.col-sm-4’ grid-class).
  2. The zipCode validatorBecause Zip Codes vary between countries you’d (might) need to set different patterns for different countries. Fortunately the plugin already provides a solution for several countries. By default it would validate based on the US Zip Code pattern. I have set the validation to that of Italy.
Warning! I had to change name and ID in the existing form to submitted because of an issue with the plugin!
Custom styling of the error messages

I wanted a popover-like style for the error messages. The plugin provides a popover option. But I with that option a popover only shows when you hover directly over an icon. To create a ‘popover’ that pops up automatically when the input is wrong I had to write some custom styling (for the error state help-block):

The style rules for the class difposhelpblock were necessary to position the help block correctly for the gender radio-inline buttons. You need to add the class ‘difposhelpblock’ for to the div that contains both the label and the input fields for gender in the form.

9 comments

Herman - February 26, 2016 Reply

Thanks. A very nice example to play with!
I’ve noticed that you declare the messages in two places.
1. On the field control
2. In the script
You do not need to place these messages in two places, As a matter of fact, since the one on the field control takes precedence,
it could cause you to pull out your hair because your message in the script is not being displayed.
This could lead to early male pattern baldness.

Have a good day,
Herman.

Theo - February 26, 2016 Reply

Hi Herman,

Agree. If you only include the field control that will suffice. For the purpose of showing a complete script I preferred including the messages. But agree with you that this might lead to confusion.

dicky - August 22, 2015 Reply

Thanks, it’s very helpful for my project 😀

Jack - May 19, 2015 Reply

Hi Theo,
Thanks for replying so quickly 🙂

Yeah I got the error after I inserted your new code which you sent me. So are you saying I should delete the script?
If so can you please explain exactly which script I should delete. If you want, I can post my entire html page here which includes the javascript. Then you could tell me exactly which lines of code to delete. I am not in a position to get any commercial solution as I am still at university and on a student salary. I think cleaning up errors in my code is the best option for me 🙂

Thanks again for your replies and your help 🙂

Theo - May 19, 2015 Reply

Hi Jack,

this little script (from the tutorial “Bootstrap 3 Contact Modal) should be deleted if you also use the Validation plugin:

http://tutsme-webdesign.info/bootstrap-3-contact-modal/#thankyou_script


"$('#send_btn').popover({content: 'Thank You'},'click');"

JACK - May 18, 2015 Reply

Hi Theo many thanks for correcting the error with my email.php file, the form is now working on my website and a successful form submission redirects the user back to the home page which is great.

There is still an issue with the validation, the popover effect shown in your tutorial is not working, instead a blank page is loaded which displays the results from this part of the code:
function died($error) {
// your error code can go here
echo “We are very sorry, but there were error(s) found with the form you submitted. “;
echo “These errors are shown below.”;
echo $error.””;
echo “Please go back and correct errors, then try again.”;
die();
}

While this is ok, the popover validation effect is not working. Also after a successful form has been submitted the “thank you” popover stays permanently on the form even after it has been closed and re-opened which is obviously an error. Is there a problem with my javascript code used for validation?

Theo - May 18, 2015 Reply

Hi Jack,

The validation demo with popover effect doesn’t produce any error messages on my side. So I guess there must be something not correct with your code. BTW Did you get this error message when you included my Thank you popover? In that case, delete that script. As mentioned in the tutorial you get strange effects if you try to combine it with this (free) validation plugin.

If you do want to use the Thank you popover script with the validation plugin I’d recommend using the commercial version of the plugin (which you can find here: http://formvalidation.io/ ). With that version of the plugin you can disable the submit button until there are no invalid fields. You can find a code example here: code example. If you insert the Thank you popover script into the final part of the second code example “Enabling the submit button when there is no invalid fields” (tied into the ‘success.field.fv’ part) I expect my little script to work correctly. Haven’t (yet) bought the commercialised plugin, so couldn’t test it for you.

Cheers, Theo

Jack - May 12, 2015 Reply

Hi and thanks for these great tutorials. I am having problems with the validation of the modal contact form, i have tried the html option, and the javascript option but each time it does not work. I can send a blank message from my contact form and then I arrive at a blank page even though I have set the destination url correctly. Can you help me out?

Theo - May 13, 2015 Reply

Hi Jack,

These issues are probably caused by a typo somewhere in your php file. I have send you the php file as used in the demo.

Cheers, Theo

Add your comment

Related Posts