Friday, 21 October 2016

HTML5 Form Validations

By,
Rahul


HTML5 provides new input types and attributes which helps us to perform client side validation of our forms in the browser itself i.e no javascript required. To start with using new attributes and input types you don’t really need do anything other than start using the new input types and attributes. Strictly you should make sure you are using the HTML5 DOCTYPE, otherwise you will run into HTML validation errors. But great thing about them is that they all degrade gracefully. So if an older browser doesn’t support them, the fact that they are in the THML won’t break anything, they will just be rendered as an <input type=”text”>.HTML5 form validation is supported by almost all the latest browsers and most mobile browsers.

New Input types
Following are some of the new input types provided by HTML5:
1. Input type=”email”
By changing input type to email, the browser can be used to validate (in a limited fashion) email address.
Example:
Email Address: <input type=”email” name=”email”>

2. Input type=”URL”
In the similar fashion to the email input type, this one is designed to accept only properly formatted URLs.
Example:
Website: <input type=”url” name=”website”>
We can improve its behavior using pattern attribute.
Example:
Website: <input type=”url” name=”website” pattern=”https?://.+”>
Now our textbox will only accept starting with http:// or https:// and at least one additional character.

3. Input type=”number”
This will accept only numbers.
Example:
Age: <input type=”number” name=”age”>
In addition we can use min and max attributes to set range.
Example: to accept age between 10 to 20 years.
Age: <input type=”number” name=”age” min=”10” max=”20”>

4. Input type=”range”
The number and range both input types parameters min & max. But main difference between both is number input typically displayed as a ‘roller’ and range input displayed as a ‘slider’.
Example:
Satisfaction: <input type=”range” size=”2” name=”satisfaction”>
We can set min, max and value attribute. By setting value attribute by default slider will set to particular provided value and by setting min and max we can set minimum and maximum value to slider.
Example: input with following conditions minimum 1 maximum 10 by default 5.
Satisfaction: <input type=”range” min=”1” max=”10” value=”5” name=”satisfaction”>

New Attributes
1.Required:
This attribute states that this field is mandatory. We can use this attribute with most of the input types.

2.Pattern:
This attribute helps us to set custom validation. This works in a same fashion to regular expression.