Themeforest

jQuery Animated Error Messages & Form Validation

In today’s tutorial we are going to use jQuery animation to create more interesting and engaging form validation errors for a user registration form.

Our jQuery form submit and validation code is based on the same one we created in our “Create Your Own jQuery AJAX Form Submit With Validation” tutorial in February. The additional items that we are going to add are:

  • An additional code snippet to check that the user’s password re-entry matches
  • jQuery code that will create & dynamically position our various validation error messages
  • jQuery animation code that will show the relevant error
  • An additional step that will fade out the error message when the input element gains focus

View DemoDownload Source Files

The Form HTML

A standard form with the same format that we used in the earlier tutorial:

<form id="form-sign-up" class="styled" action="" method="post">
    <fieldset>
        <h3>Register Now!</h3>
        <ol>
            <li class="form-row">
                <label>Name:</label>
                <input name="name" type="text" class="text-input required" />
            </li>
            <li class="form-row">
                <label>Email:</label>
                <input name="email" type="text" class="text-input required email" />
            </li>
            <li class="form-row">
                <label>Password:</label>
                <input name="password" type="password" id="password-1" class="text-input required password" />
            </li>
            <li class="form-row">
                <label>Repeat Password:</label>
                <input name="password1" type="password" id="password-2" class="text-input required password" />
            </li>
            <li class="button-row">
                <input type="image" src="images/btn_sign_up_off.png" alt="Sign Up" value="OK" class="btn-submit img-swap" />
            </li>
        </ol>
    </fieldset>
</form>

The key items here are the classes we have assigned to the text elements, which will be used by our jQuery code to identify what validation rules and error messages should apply. We have 3 different types:

  • Name – has class “required”, which checks that the input is not empty and is used as the basis for all of our form elements
  • Email – has class “email”, which checks the input against a regular expression for matching standard email formats
  • Password/Re-enter Password – has class “password”, which will check the 2 entries against each other to make sure they match

Our Form CSS

There are a couple of CSS rules, which are required in order for our error animation to work – these are highlighted in the code below with appropriate comments:

/*Form styles*/
.styled {
font: 15px Arial, sans-serif;
width: 422px;
margin: 20px auto;
background: url(images/bg_form.png) no-repeat 0 0;
padding-top: 20px;
}
.styled fieldset {
background: url(images/bg_form.png) no-repeat 0 100%;
padding: 0 25px 20px 25px;
position: relative;
}

/* Form rows */
.styled fieldset li.form-row {
margin-bottom: 5px;
padding: 3px 0;
clear: both;
position: relative; /* Required as error messages will be absolutely positioned */
}
.styled label {
display: block;
font-weight: bold;
float: left;
width: 100px;
line-height: 24px;
padding-top: 4px;
color: #555;
}
.styled fieldset li.button-row {
margin-bottom: 0;
padding: 5px 0 0;
text-align: right;
}

/* Text input styles */
/* Default */
.styled input.text-input {
height: 22px;
width: 254px;
padding: 5px 8px;
background: url(images/bg_input.png) no-repeat 0 0;
border: none;
font: normal 15px Arial, sans-serif;
color: #333;
line-height: 1em;
}

The Form Validation CSS

The following CSS rules are for styling and setting up the form error messages:


/* Form Validation */
/* CSS code to create the error messages */
.styled span.error {
font: bold 11px Arial, sans-serif;
line-height: 1em;
color:#fff;
text-shadow: 1px 1px 1px #000;
background: url(images/arrow_error.png) no-repeat 0 center;
border-right: 1px solid #6c0202;
height: 11px;
padding: 8px 15px 11px 20px;
display: none; /* Required as we will use jQuery to fade in the error message */
position: absolute; /* Required */
top: 3px;
right: 0; /* Required - initially set all error messages to the right of the form row */
}

/* Change the input field styles when an error message is present */
.styled fieldset li.error input.text-input {
background-position: 0 -64px;
}

The jQuery Code

The code below includes comments explaining each function in more detail:

// Form validation and submit when button is clicked
	$('.btn-submit').click(function(e){

		// Declare the function variables:
		// Parent form, form URL, email regex and the error HTML
		var $formId = $(this).parents('form');
		var formAction = $formId.attr('action');
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		var $error = $('<span class="error"></span>');

		// Prepare the form for validation - remove previous errors
		$('li',$formId).removeClass('error');
		$('span.error').remove();

		// Validate all inputs with the class "required"
		$('.required',$formId).each(function(){
			var inputVal = $(this).val();
			var $parentTag = $(this).parent();
			if(inputVal == ''){
				$parentTag.addClass('error').append($error.clone().text('Required Field'));
			}

			// Run the email validation using the regex for those input items also having class "email"
			if($(this).hasClass('email') == true){
				if(!emailReg.test(inputVal)){
					$parentTag.addClass('error').append($error.clone().text('Enter valid email'));
				}
			}

			// Check passwords match for inputs with class "password"
			if($(this).hasClass('password') == true){
				var password1 = $('#password-1').val();
				var password2 = $('#password-2').val();
				if(password1 != password2){
				$parentTag.addClass('error').append($error.clone().text('Passwords must match'));
				}
			}
		});

		// All validation complete - Check if any errors exist
		// If has errors
		if ($('span.error').length > 0) {

			$('span.error').each(function(){

				// Set the distance for the error animation
				var distance = 5;

				// Get the error dimensions
				var width = $(this).outerWidth();

				// Calculate starting position
				var start = width + distance;

				// Set the initial CSS
				$(this).show().css({
					display: 'block',
					opacity: 0,
					right: -start+'px'
				})
				// Animate the error message
				.animate({
					right: -width+'px',
					opacity: 1
				}, 'slow');

			});
		} else {
			$formId.submit();
		}
		// Prevent form submission
			e.preventDefault();
	});

	// Fade out error message when input field gains focus
	$('.required').focus(function(){
		var $parent = $(this).parent();
		$parent.removeClass('error');
		$('span.error',$parent).fadeOut();
	});

The comments are fairly self explanatory. So to briefly summarise the jQuery code:

  1. When the submit button is clicked the validation process starts by declaring all function variables, including the error message span tag
  2. Clean up the form by removing any errors span tags plus the error class on the form rows from the previous click so we are starting with a clean slate
  3. Loop through all input fields with class “required” and first check if they contain text
  4. Validate input fields with class “email” using a standard regex pattern for email address formats
  5. Get the 2 password field values and check if they match
  6. If any of our checks returns an error indentify that form row by adding class=”error”, clone the error span tag, append to the form row and insert the relevant error message text
  7. Position each error message span tag to the right of the form row based on the total width of the message
  8. Fade in each error message and alert the user by animating 5px to the left
  9. Fade out and remove the errors when the user clicks on the text input field

With the basic process now in place you can easily modify and expand the animation functions and try different effects to suit your users and website.

View DemoDownload Source Files

17 Comments

  • This is a fantastic script but i am have trouble saving the form information to a database. any advice?

    • Hi,

      Saving to a database is not really considered in this tutorial as we are only covering client-side functions with jQuery

  • great and awesome script thanks a lot although it was a bit tricky to make it send the data to a php file through ajax but i made it (am not a jquery experts actually ) anyway thanks a lot

    • Hi,

      Thanks. Glad you managed to get it working

  • Thanks for this scripts its great! However having issues with it working in ie6 not sure why? Did you run into it and is there any way to make sure it works in that browser too?

    • Hi,

      Unfortunately we no longer support IE6

  • First off, this script is great!

    I was wondering if there was a way to add another ‘check’ for a certain number of characters.

    For example, I want my password to be at least 6 characters. It would be great if I could get it to show the alert “Minimum 6 characters” when the button is pressed if the password is not long enough.

    Any insight you could provide would be greatly appreciated!

    Cheers!

    • Hi,

      We can add an additional validation rule that checks number of characters using regular expressions. The regex for 6 characters would be – /^([a-zA-Z0-9]{0,6})$/

      The additional jQuery to test the rule:

      // Check minimum characters = 6
          if($(this).hasClass('min-6') == true){
              var characterReg = /^([a-zA-Z0-9]{0,6})$/;
              if(characterReg.test(inputVal)){
                  $parentTag.addClass('error').append($error.clone().text('Minimum 6 characters'));
              }
          }
      

      In this example we use class name “min-6″ for any input fields, which need validation. I have uploaded a demo page – http://www.designchemical.com/lab/jquery/demo/jquery_animation_form_validation_errors_2.htm

      There is also an earlier post, which has other examples of regular expressions for various types of validation – Form Validation Using jQuery and Regular Expressions

  • [...] jQuery Animated Error Messages & Form Validation [...]

  • I am unable to submit the form on second time. for first time it is working well.. bt when i click the button for second tim the validation works well bt the code behind the button dsnt wrk.

    • Hi – check if your jQuery has any errors. The code should submit as many times as required so I can only assume there is a problem somewhere

  • Sorry for the multiple posts. The HTML still isn’t showing. Hopefully you can extract it from your comment system. Otherwise, I can email it to you.

    • Have sent you an email.

  • Lee,

    I haven’t been able to figure out how to modify the scripts included in the downloaded file I got from http://www.designchemical.com/lab/jquery/demo/download/jquery-animation-form-validation-errors.zip so that they fit the classes and IDs in the markup being generated by my theme AND what I need to add to trigger the script.

    As I said, this is a bit beyond my skill level. I’m not a complete novice, and can follow instructions, so your help would be greatly appreciated.

    FYI, this is a cleaned up copy of the HTML (hopefully your comment system won’t strip it out:

    <
    Let us know what you think:

    Name *

    Email Address *

    BTW, I’ve tested all of the WP plugins that claim to provide JS validation, but none seem to work, so there’s an opportunity for you to add to your great collection of plugins.

    Thanks.

  • With my meager programming skills, I’ve been trying to implement the validation techniques you’ve been showing for the WordPress comment system. Clearly, I’m not up to the task. Any chance you’re planning on rolling all of this into a WP plugin? I hope so, but will keep following your tutorials in any event. Thanks.

    • Hi efaps – its certainly something we can look at. What problems are you having?

  • [...] jQuery Animated Error Messages & Form Validation This tutorial by Design Chemical shows you how to use jQuery animation to create more interesting [...]

Leave a comment

To add code to your comments wrap the code text in [text][/text] tags