Trigger HTML5 form validation onblur using jQuery and checkValidity

HTML5 form validation is in my view one of the nicest things in HTML5. It makes it very easy to implement form validation, and you avoid writing your own validator or implementing some custom jQuery-plugin – which improves load time and reduces complexity of the solution.

As you probably know, the HTML5 form validation works by adding different attributes to the input element. The code below will make sure that the user only inserts a number in the range of 1000 to 9999. The user will not be able to submit the form unless the correct number has been inserted.

<input type="text" name="zipcode" placeholder="Insert zip-code" class="zipcode" min="1000" max="9999" maxlength="4" size="4" required="required">

However, this validation is only triggered when the user tries to submit a form. Clicking submit will produce an error message, and nothing will be sent to the server. I had a certain case where I needed to validate each input-field onblur.

In this case, you can use the checkValidity-method in the constraint validation API. (You can read more about this API in the following blogpost: http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/). The checkValidity-method can be applied to each input-element and will return true if the value of the input-element is valid. Otherwise, it will return false.

I therefore ended up applying the following small jQuery-snippet in order to add form validation onblur:

$('#wizardvalidator input').blur(function(e) {
	var controlgroup = $(e.target.parentNode);
	if (!e.target.checkValidity()) {
		controlgroup.removeClass('success').addClass('error');
	} else {
		controlgroup.removeClass('error').addClass('success');
	}
});

The code above checks each and every input-element onblur and adds the necessary classes in order to display a validation-state to the user.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s