Benjamin Tinker Team : Web Development

jQuery Email Validation when the user is done

Benjamin Tinker Team : Web Development


jQuery has some great validation tools for forms. Using the validation plugin from http://jqueryvalidation.org you have access to a wide range of methods that can validate most any form field and control you place on your page. Using the validation controls takes away most of the busy work for ensuring content is valid before being sent to the server.

One common check is ensuring a email address is valid. You may have a very simple form such as the one below that collects the users email for newsletter subscriptions:

<form id="myForm" action="/processSubscription" method="post">
<label for="emailAddress">Email</label>
<input type="text" name="Email" class="required">
<input type="submit" value="Submit">
</form>

We want to ensure that the Email field only contains a valid email address. jQuery validate will check the field is valid as you type however this is not always desirable in the case of Email addresses. We want our user to finish entering their email address before we check if it is valid or not. By adding in the following code we can hook in the jQuery form validation to ensure the Email field contains a value.

// -------------------------------------------------
$('#myForm').validate({
	errorClass: 'error',
	messages: {
		Email: {required: 'Email is required'}
	},
	rules: {
		Email: {required:true}
	}
});

As we only want to validate the email address after loosing focus on the field we need to hook in an event that adds the email check rule upon loosing focus of the field. We also need to remove the rule upon focus so it will wait for the user to finish entering their address before validation.

$('input[name="Email"]').on('blur', function () {
	$('input[name="Email"]').rules('add', { email: true, messages: { email: 'Invalid email address' } });
	$('#myForm').valid();
}).on('focus', function () {
	$('input[name="Email"]').rules('remove', 'email');
	$('#myForm').valid();
});

The above code dynamically adds and removes the email validation rule as the user focuses and clicks away from the email field. It also forces the form to validate with each operation to determine if the error message should be shown or not.

You can use this technique to add in dynamic validation rules to any form. The benefit is that you can procedurally add in only those rules you need and remove them if unnecessary. It keeps your validation clean and only does the checks that are necessary.