HTML5 Recipes: Form Validation

We shall conclude looking at HTML5 form features by discussing form validation in this recipe. Form validation is an important feature of any web application that takes input from the user. To validate form data before submission to the server side, developers have written custom Javascript code to validate the input field data and various mechanisms to display client side validation errors have been employed. With HTML5, a large part of this work is likely to get done by the browsers as they implement HTML5 support.

We have covered the use of the required attribute on any input field to indicate to the browser that the particular field is required and should be provided by the user. There is another attribute called pattern that we can apply to any text input element. The value for the pattern attribute is a regular expression that will be used by the browser to validate the data entered in that field. This can be used as a mechanism to validate your field if it does not fit within the type attributes that we covered earlier, like email, url, etc

Let us look at some example code below that employs the required and pattern attributes to validate the input data. The results are best seen in a browser that implements them well and currently Opera is the best of the lot. I strongly suggest to view this link in Opera to understand how browsers are likely to implement it.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML5 Form Elements</title>
</head>
<body>
<form id="registrationform" action="submit.jsp" method="POST">
    <label for="username">Username</label>
    <input name="username" id="username" type="text" required autofocus /><br/>
    <label for="firstname">First Name</label>
    <input name="firstname" id="firstname" type="text"  placeholder="Your First Name"/><br/>
    <label for="lastname">Last Name</label>
    <input name="lastname" id="lastname" type="text"  placeholder="Your Last Name"/><br/>
    <label for="email">Email</label>
    <input name="email" id="email" type="email"  placeholder="Your Email Address" required/><br/>
    <label for="phonenumber">Phone Number</label>
    <input name="phonenumber" id="phonenumber" type="text"  placeholder="Your Telephone Number" required pattern="^D?(d{3})D?D?(d{3})D?(d{4})$"/><br/>
    <button type="submit">Register</button>
</form>
</body>
</html>

Let us break the code down now:

  • We have a simple HTML5 form over here that allows the user to fill out some fields and submit it.
  • We have 3 form fields marked with the required attribute i.e. username, email and phonenumber. This means that if you do not enter a valid value for the field, then the browser should prompt about it and will not submit the form to the Server i.e. the server resource that we have identified in the action attribute.
  • The phonenumber field also has a pattern attribute set. Its value is a regular expression that allows you to enter any US phone number. The value will be validated against this regular expression by the browser.

If I do not enter any value and click on the Register button, I see the following prompt in the Opera browser:

valform1.png

If I do not enter a valid format for either the email field or the phone number field, I see the following messages in the Opera browser respectively.

valform2.png

See it in action here.

If the browser does not implement the HTML5 form validation features correctly, you will find that the form will get submitted unlike the current Opera browser that prevents submission if you put in invalid values.

Let us also take a look at how you could perform the same validation via code. This could be useful in scenarios where you want to override the default form validation behavior or even in cases where the form validation is not as slickly implemented like in Opera, for example.

Take a look at the code below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML5 Form Elements</title>
<script type="text/javascript">
function checkEmailField(){
    var emailelement = document.getElementById("email");
            if (emailelement.validity){
                if (!emailelement.checkValidity()){
                    alert("The Email Id is not valid");
                }
                else {
                    alert("The Email Id is valid.");
                }
            }
}
</script>
</head>
<body>
<form id="registrationform" action="submit.jsp" method="POST">
<fieldset id="inputs" style="border: 1px solid #000;border-radius: 6px;">
    <label for="username">Username</label>
    <input name="username" id="username" type="text" required autofocus /><br/>
    <label for="firstname">First Name</label>
    <input name="firstname" id="firstname" type="text"  placeholder="Your First Name"/><br/>
    <label for="lastname">Last Name</label>
    <input name="lastname" id="lastname" type="text"  placeholder="Your Last Name"/><br/>
    <label for="email">Email</label>
    <input name="email" id="email" type="email"  placeholder="Your Email Address" required/><br/>
    <label for="phonenumber">Phone Number</label>
    <input name="phonenumber" id="phonenumber" type="text"  placeholder="Your Telephone Number" required pattern="^D?(d{3})D?D?(d{3})D?(d{4})$"/><br/>
    <button type="submit">Register</button>
    <button type="button" onclick="checkEmailField()">Validate email</button>
</fieldset>
</form>
</body>
</html>

Let us break the code down now:

  • The code is same as the previous example , except that we have added a button Validate email that will invoke thecheckEmailField when clicked.
  • For sake of simplicity, I am only demonstrating how to validate the email field but you could apply it to any number of fields that you want. The checkEmailField gets a reference to the email input field and it first checks if it supports validation. If yes, it simply invokes the checkValidity() method on it. This will automatically kick in the validation expected from the form field depending on what you have specified i.e. required or any pattern or any particular type. It will then display an appropriate message if the validation passes or not.

See it in action here.


HTML5 Forms Recipes

  1. New features in HTML5 for Forms
  2. New Form Elements
  3. Form Validation

Back to HTML5 Series

 

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