Wednesday, 27 August 2014

Validating form elements using the new Html 5 required and pattern attributes.

Introduction


Html 5 has come a long way since the first draft appear sometime around 2010, and since that time most of the browsers has been in a catch-up race (though as at this moment most of the latest browsers are up to date). In this post, we will learn how the use the required and pattern attribute, which are part of the new goodies that html 5 brought with it to ease the web developers life.

So whats this required attribute?

The required attribute  is just a boolean attribute that determines whether the browser will submit a form whose elements marked with the attribute contains a value. Yeah I know that the definition made your head spin. What the required attribute does is just to tell browser that a value is"required" in any form element marked with the attribute. So if the form is being submitted and the browser sees that a form element marked with the attribute does not contain a value, the browser will prevent the form from being submitted. This attribute is usually used in those elements where the user is expected to input a value like the input elements (no pun intended). For example:

< input required name='email' >  

OR 

< input required='required' name='email' />

NB:
Now both attributes are the same, the type you choose will depend on will land you are coming from (html or xhtml).

What about the pattern attribute?

The pattern attribute is an attribute used to specify a regular expression which the browser will used to validate the value entered by the user. Validation has been done for centuries (alright for sometime since the inception of the html and javascript) using javascript. What it does is to tell the browser to validate whatever value entered by the user into the form tag marked with the attributes' regular expression. Likewise it is mostly used on input elements. An example of its use are:

< input type='text' name='email' pattern="[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}" />


What if the browser does not support this new attributes?

Whenever you are using html 5 and css 3 and you plan accommodating old browsers like the brothers in crime (internet explorer 6 - 8), you should try as much as possible to provide 'javascript polyfills' (ie: javascript implementation of the functionality that you are trying to use) as a fallback so that non-supporting browsers can still achieve the same function. You can  find free ones online or write your own depending on what you are trying to achieve like the one shown below



(function(){

    //Check if input natively supports the required attribute
    //using modernizr
    if( !Modernizr.input.required){

        //if not
        //Get the form element and hook up on submit
        // event handler to it
            var form = $('form');

        //on submit event handler
        form.on('submit', function(){
            var input = $('[required], [pattern]'),
                submitBtn = $('input[type="submit"]'),
                result = true;

            submitBtn.attr('disabled', 'disabled');

            input.each(function(){
                var self = $(this);

                if(self.val() === ""){
                    self.toggleClass("required");
                    result = false;
                }
                else{
                    var pattern = self.prop('pattern');

                    if(pattern !== null && pattern !== 'undefined'){
                        var value = self.val(),
                            regExp = new RegExp(pattern);
                        if(!regExp.test(value)){
                            result = false;
                            self.toggleClass('required');
                        }
                    }

                }
            });

            if(result === true){
                submitBtn.removeAttr('disabled');
            }

            return result;
        });
    }

})();

Conclusion

Using the new html 5 validation attributes is really the best and latest way to go at the moment as most recent and even not so recent browsers already has support for it.Whereby support is not provide you can then fall back to using javascript for the validation. For a complete example of where this attribute has been used together, click here to fork the code example from my github repo. Happy coding.



No comments:

Post a Comment