Integrating the jQuery Validation plugin with Twitter Bootstrap

Posted by on Oct 22, 2012 in CodeIgniter, jQuery | 5 Comments

Twitter Bootstrap has some nice styling for error messages in forms. Using jQuery form validation could come handy and its actually pretty easy to integrate. The question is, how do we use the Bootstrap styling along with jQuery Validation plugin? Read on for more.

I actually wanted to:

a) All the form errors should be displayed in a single alert above the form.
b) Fields with errors should be marked in red.
c) BONUS: CodeIgniter fields should ALSO be displayed in the single alert above the form.

Lets get started:

1. Download the jQuery Validation plugin and the Twitter Bootstrap framework and install them according to your app structure.

2. In your app .js file or wherever you are placing your JS code, add the following function:

/* Sets some stilying for validating forms */
function setValidatorDefaults(errorHandler, message){
	$.validator.setDefaults({
		showErrors: function(errorMap, errorList) {
			var validation = this;
			if(validation.numberOfInvalids() > 0)
				$(errorHandler).html(message);

			$(errorList).each(function() {
				var error = this;
				validation.settings.highlight(error.element);
			})

			for (var i = 0, elements = this.validElements(); elements[i]; i++) {
				validation.settings.unhighlight(elements[i], validation.settings.errorClass, validation.settings.validClass);
			}
		},
		highlight: function(element) {
			$(element).parents('.control-group').addClass("error");
		},
		unhighlight: function(element) {
			$(element).parents('.control-group').removeClass("error");
		},
		onfocusout: false,
		onkeyup: false,
		onclick: false
	});
}

3. Now whenever you want to validate a form, use the following JS structure:

setValidatorDefaults('.errorHandler', '<div class="alert alert-error"><strong>Ooops!</strong> Please complete all the fields to continue.</div>');

$("#friendly_form").validate();

4. In your HTML code, you should also have a .errrorHandler div that should be empty and not styled. This div will be used to place the error code coming from the Validation plugin

<div class="errorHandler"></div>

5. BONUS for CodeIgniter users: lets say you are using CodeIgniter and you also want to display your form errors in the same alert message. Just add the following to your .errorHandler div inside your HTML code:

<div class="errorHandler">
<?php echo $this->form_validation->error_string('- ', '<br />', '<div class="alert alert-error">', '</div>'); ?>
</div>

How come the error_string method has 4 parameters?, you might ask. Actually, the explanation for that is an extension of the CI Form Validation Library. Just add the following to a file called MY_Form_validation.php and save it to /application/libraries/

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation
{
	/**
	 * Error String
	 *
	 * Returns the error messages as a string, wrapped in the error delimiters
	 * NEW!: Added a global wrapper, useful for Bootstrap styling
	 *
	 * @access	public
	 * @param	string
	 * @param	string
	 * @return	str
	 */
	public function error_string($prefix = '', $suffix = '', $global_prefix = '', $global_suffix = '')
	{
		// No errrors, validation passes!
		if (count($this->_error_array) === 0)
		{
			return '';
		}

		if ($prefix == '')
		{
			$prefix = $this->_error_prefix;
		}

		if ($suffix == '')
		{
			$suffix = $this->_error_suffix;
		}

		// Generate the error string
		$str = '';
		foreach ($this->_error_array as $val)
		{
			if ($val != '')
			{
				$str .= $prefix.$val.$suffix."\n";
			}
		}

		return $global_prefix.$str.$global_suffix;
	}
}

/* End of file MY_Form_validation.php */
/* Location: ./application/libraries/MY_Form_validation.php */

If you have any comments, improvements or questions about this, feel free to go on in the comments section below. Enjoy and happy coding!

5 Comments

  1. Validação com CodeIgniter, Twitter Bootstrap e jQuery Validation plugin | CodeIgniter Brasil
    November 5, 2012

    [...] do negócio para o projeto ser um sucesso! Este artigo é altamente inspirado no post “Integrating the jQuery Validation plugin with Twitter Bootstrap” do blog de Bastian [...]

    Reply
  2. Mr. Don
    January 7, 2013

    btw where is the demo??????????

    Reply
  3. Pictoru
    January 8, 2013

    Did you tried to use jQuery Validation plugin within Bootstrap Modal popup?

    I tried but the fields just don’t trigger well. Do you have any suggestion?

    Reply
  4. Pictoru
    January 8, 2013

    It seems was my mistake. The test form I used hadn’t names to the fields and seems validation plugin don’t like it. Anyway… your posts are extremely useful.

    Thanks!

    Reply
    • Danny Herran
      January 8, 2013

      Glad it worked out for you. Happy coding!

Leave a Reply