HTML5 Validation


I recently got asked what HTML5 validation looks like.

Needless to say this was a bit of a strange question, but as I read on through the question, I realized that is wasn’t a case of not knowing what HTML5 validation looks like, but a case of where jQuery validation stopped and the HTML5 stuff started.

In this quick post, I’m going to briefly cover the HTML5 validation stuff in the hopes it’ll clear a few things up.

It all starts with a tag.

The validation services now available in HTML5 start with a change in the types available in the ‘input’ tag when you create a form. Usually for text boxes you specify a type of ‘text’ for the type attribute, from H5 onward however you have a dazzling array of types as follows:

  • search
  • email
  • url
  • tel
  • number
  • range
  • date
  • month
  • week
  • time
  • datetime
  • datetime-local
  • color

In general most of these types are now well supported in the modern browsers, but best to test as there are still a few odities. Also the usual warnings about less than IE9 etc apply too. Always check places like Can I Use to verify the browsers your thinking of targeting.

So how do these input types help us?

If you define an input tag for example as an Email type:


<input type="email" name="txtEMail" id="txtEMail" />

You should get something that looks just like a normal form element:

HTML5 email form element

Looking at it as a casual observer you might be forgiven for thinking there’s no difference, but now, lets try entering some data into that’s not an email address, and then submitting the form:

HTML5 email element with validation warning

Immediately you see that the browser is now telling you, something is wrong with the input, and all because you changed the value of an attribute, on your tag.

You can also go one further too and use the new css3 pseudo classes to style your elements. If your using bootstrap3, you should see that you get appropriate coloring around your elements already, but an explanation of that will have to wait until another day, for now add the following CSS rules to an example HTML5 page, and mark up a simple test form as follows:


<!DOCTYPE html>
<html>
<head>
  <title>HTML5 Validation test</title>
  <style>
    .myInput:valid
    {
      border: 2px solid green;
    }

    .myInput:invalid
    {
      border: 2px solid red;
    }

  </style>
</head>
<body>
  
  <form method="get" action="#" id="myForm" >
    
    <label for="txtEMail">EMail:</label>
    <input class="myInput" type="email" name="txtEMail" id="txtEMail" />
    
    <input type="submit" value="submit" />

  </form>


</body>
</html>

If you put this into an HTML page and render it in your browser, you should see the border of the input element change, depending on if the input text is a valid email or not. The astute reader among you will also notice that having nothing in the box is also valid, this is deliberately by design in case you want a form where the email address is not mandatory.

If you want to make the email address mandatory, then you add an extra validation attribute called ‘required’.


<input class="myInput" type="email" name="txtEMail" id="txtEMail" required />

This will then force the validation to fail if the field has no value in.

HTML5 email field showing required warning

There are a number of other validation attributes you can add too, such as specifying a regular expression to match against, a good place to look all of these up (and more) is HTML Doctor , on there you can find reference material thats by far much easier to read and digest that the official W3G specifications.

If you wanted too, and where happy with the browsers default styling, you could leave it there and just mark your forms up as required. Your form will simply NOT be submitted by the browser if any of your validation rules cannot be applied, meaning that should you wish to you actually don’t need any client side code to help you.

However, if you want to override the default browser styles and put your own toast notifications or alerts up on screen, then you do need to start digging into a little bit of JavaScript.

Change your page markup so that it now matches the following:


<!DOCTYPE html>
<html>
<head>
  <title>HTML5 Validation test</title>
  <style>
    .myInput:valid
    {
      border: 2px solid green;
    }

    .myInput:invalid
    {
      border: 2px solid red;
    }

  </style>
</head>
<body>
  
  <form method="get" action="#" id="myForm">
    
    <label for="txtEMail">EMail:</label>
    <input class="myInput" type="email" name="txtEMail" id="txtEMail" required />
    
    <input type="submit" value="submit" />

  </form>
  
  <p id="warning"></p>

  <script>
    
    // Notice we're not using jQuery, thats why we put the JS at the bottom
    // and don't let it run until the HTML above is loaded
    
    // The first thing have to do, is temporarily turn off the form validation
    var form = document.getElementById("myForm");
    form.noValidate = true;
    
    // Then we attach our submit handler
    form.onsubmit = validationHandler;

    // This is our validation function
    function validationHandler()
    {
      // we need to grab the fields we wish to validate
      var emailField = document.getElementById("txtEMail");

      // Then get a true/false of the field state
      var result = emailField.checkValidity();

      // And let the form know if it can submit or not
      var warning = document.getElementById("warning");
      if(result == false)
      {
        warning.innerText = "Form is NOT valid!";
        return false;
      }
      else
      {
        warning.innerText = "";
        return true;
      }

    }

  </script>

</body>
</html>

You’ll see that the overall markup and CSS rules are the same, but we now have a chunk of JavaScript added. You’ll notice also that this is now placed at the bottom of the page.


Current best practice in the industry now recommends that ALL script tags that include files or produce inline code be placed at the bottom of the document now, this is for 2 main reasons, the first is that jumping in and out of script context switches, and slows down the page rendering. The second reason is that the page contents by that point are usually fully formed, and all DOM objects are pretty much guaranteed to be present, which means no JS errors about missing elements, and very little requirement for things like jQuery document ready handlers.

By putting the JS code at the bottom we don’t need jQuery to help us target our elements, instead we can simply use the new HTML5 apis such as getElementById() and grab the DOM node directly, instead of having to get a jQuery object, then convert it.

Use the API Luke…

Many of you will recognize, that I’m trapping the submit handler for the form (Just as you may have done in older versions of HTML), this is still the mainstay way to grab the form before it gets sent across the wire and check it. However, what we actually need to do (as you can see in the code) is turn off form level validation.

At this point you might be thinking, surely that defeats the object right? But no it doesn’t, well not quite anyway.

With the form level validation turned on, HTML5 validation is performed before the submit click is processed. This means that your submit handler will never get called as long as the validation rules cannot be applied. Turning the form validation off, allows you to fire the submit handler, and then return either a true or false value as you normally would, to allow the form submission to continue.

Where the new API comes into it’s own, is when you start actually looking at the new methods and properties that are now available on correctly marked up elements.

In our code above, you’ll see this line:


var result = emailField.checkValidity();

The checkValidity() function is one of the new additions to the HTML5 Validation API, and returns a true or a false (or undefined if the browser is not able to understand it), where true means the input you checked is in a valid state and anything else means it’s not or your unable to determine the state.

If you run the page and attempt to submit a form with an invalid email, you’ll now get this:

Email element with custom not valid message

And that’s pretty much it, well the very basics anyway. There’s many more CSS rules to look at, and a whole bunch more method calls in the API to make use of. However, as long as your elements are marked up correctly, then you can easily call checkValidity() on the element any time you like and it will tell you if the input’s state is or is not valid according to the rules you asked it to check.

Remember also, to use things like ‘Modernizr’ and good graceful detection practices where needed. I’ve deliberately NOT added any checking in the code in this post so that I can concentrate on just showing the mechanics of how it all works, out in production you’ll want to make sure you can accommodate those few stragglers that still use old browsers, or that don’t fully support all of this new stuff.

As of my writing this post, the above code works in:

  • Chrome 38
  • Firefox 33
  • IE 11

If you want to peruse the topic further, then I strongly suggest reading Craig Bucklers 3 part series on Sitepoint :

HTML5 Forms and Validation (Part 1)

HTML5 Forms and Validation (Part 2)

HTML5 Forms and Validation (Part 3)

Happy validating.
Shawty

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