jQuery: form validation with HTML5

HTML5 allows us to get a finer control over form elements. In fact, with the newly introduced form attributes and values we can perform more advanced validation routines using jQuery. For example, given a form like this:

<form action="" method="post">
<ul>
<li><label for="username">E-mail</label>
<input type="email" name="username" id="username" required="required" /></li>
<li><label for="password">Password</label>
<input type="password" name="password" id="password" required="required" /></li>
</li>
</ul>
</form>

we can easily check required values thanks to the required attribute:

$('input[required]').each(function() {
    var $input = $(this);
    checkRequired($input);
});

Further, we can even perform data-specific validation routines, for example on emails:

$('input[type=email]').each(function() {
    var $email = $(this);
    checkEmail($email);
});

In this case, data-specific validation is also performed by web browsers to check if a given data type is in the correct format. Here the email value must honor the rules contained in the RFC 2822 specification.

Leave a Reply

Note: Only a member of this blog may post a comment.