Friday, May 30, 2014

Validate Form Inputs Easily On Any Browser With Validatr

Dealing with forms on the Web can be real interesting. You can do a lot of customisation in design, on the label and even on the authentication. With a lot of new features available in HTML5, Jay Morrow created Validatr which rely on the new HTML5 input attributes to perform easy and automatic form validation.

Validatr is a cross-browser free jQuery plugin. It will automatically wrap the form border in red if the user inputs an invalid value. It also can do lot of input validation like email, number, url, range, color inputs and date.

Custom error messages are also available with various choices using HTML5 data attributes. You may customize the error message element with your own CSS, and the plugin has some pretty good CSS styles.

Basic Guide

To use Validatr, Include the latest jQuery and also the Validatr script in your project.


  <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
  <script src="js/validatr.js" type="text/javascript"></script>
  

Then call the plugin with the following snippet:


  <script>
  jQuery(function ($) {
      $('form').validatr(); 
  });
  </script>
  

The plugin will recognize the form element to apply changes.

HTML Markup

As mentioned, Validatr utilizes the input element to work. The element is wrapped inside the form tag. The input element will handle all different form types and settings using HTML5 data-attribute.

For example, when you want to create number form, just add type="number" into the input and some additional requirements e.g. limiting the min and max number. If the users are not allowed to leave the form blank, just add the required attribute.

The following is a basic implementation example:


  <form action="./">
      <label for="number">Number</label> 
      <div>
          <input type="number" id='number' step=2 min=1 max=11 name="number" required>
          <input type="submit" value="Submit">
      </div>
  </form>
  

The step attribute is used for value increments when the user clicks the increase or decrease arrow in the form, starting within the defined min number or 0. If the value is set to “0″, this means it uses default increment or increased only one point (the value must be a positive number).

And here’s the result when a user inputs an invalid value or out of range number. Our example uses 2 for the step which means starting from 1, the only numbers that are valid, have an increment of 2, that is: 3, 5, 7 and so on. The max value is 11.

For a complete list of other input types and attribute documentation, please head over to the Validatr page.

No comments:

Post a Comment