An HTML5 form validation plugin for jQuery. Works on all major browsers, both new and old. Implements inline, realtime validation best practices (based on surveys and usability studies). Developed for production use in e-commerce. Currently in production with millions of users.

Overview

h5Validate (WARNING -- DEPRECATED -- ARCHIVED)

Hi,

I'm Eric Elliott, author of "Programming JavaScript Applications" (O'Reilly). A few years ago, I wrote this jQuery plugin that understands HTML5 forms and knows how to validate them, even in browsers that don't yet support HTML5.

In browsers that do support HTML5, h5Validate adds some much-needed features, such as the ability to customize the user interface when an input fails validation.

Status

A lot has changed since I wrote this library in 2010. It has been several years since I used the library myself. I leave it here because other people might find it useful. There are some open issues, and I have no intention of updating or maintaining this library myself. This project is now and will always remain unmaintained. If you would like to use this code, please fork and maintain your own copy.

Documentation

Best practice realtime HTML5 form validation for jQuery. Works on all popular browsers, including old ones like IE6.

  • Regularly tested on 13 different browsers, IE6 - IE9, FireFox, Chrome, iPhone, and Android.
  • Implements best practices based on 1,000 user survey, several usability studies, and the behavior of millions of users in live production environments.

Supported Platforms

Desktop: IE 9, 8, 7, 6, Chrome, Firefox, Safari, and Opera. Tested on Windows 7 and Mac. Mobile: iPhone, Android, Palm WebOS

Jumpstart

Copy and paste this at the end of the body on any page with an HTML5 form. If html5 validation rules exist in the form, you're in business!

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.h5validate.js"></script>

<script>
$(document).ready(function () {
    $('form').h5Validate();
});
</script>

Features

1. HTML5 required attribute

E.g.:

<input id="name" name="name" type="text" placeholder="Bob" title="Your name is required." required>

2. HTML5 pattern attribute

E.g. This expects mm/dd/yyyy:

<input id="name" name="name" type="text" placeholder="mm/dd/yyyy" title="mm/dd/yyyy" pattern="(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d">

3. Pattern library

Sometimes, you'll want to re-use the same validation pattern for several elements on a page. You could copy and paste the same pattern over and over again to a bunch of different form fields, but what happens if you discover a bug in the pattern? Fix it and repeat the whole copy and paste process?

A better solution is to attach the pattern with a class selector. Use $.h5Validate.addPatterns() to add your pattern, make sure the classPrefix variable is set correctly (it's h5- by default), and add the class to the input fields.

The included patterns available are:

  • email
  • phone
  • email
  • url
  • number
  • dateISO
  • alpha
  • alphaNumeric
  • integer

E.g.:

<input type="text" class="h5-email" required />

4. Error messages

Error divs should be hidden in the HTML with display: none; -- h5Validate shows them when the corresponding field is marked invalid.

E.g.:

<form>
    <label for="FirstName">Your Name:*</label>
    <input id="FirstName" type="text" title="Required: Please provide your first name." required>
    <div id="invalid-FirstName" style="display: none;">
        This stuff will get replaced by the title contents.
    </div>
</form>

5. Options

There are a ton of options you can override by passing key: value pairs when you call .h5Validate(). For example, we can change the CSS class that indicates validation errors:

<head>
<style>
	.black {
		background-color:#111111;
		color:silver;
	}
</style>
</head>
<body>
<form id="black">
		<label for="name">Your Name:*</label>
		<input id="name" name="name" type="text" placeholder="Bob" title="Your name is required." required>
</form>

<script>
	$(document).ready(function () {
		$('#black').h5Validate({
			errorClass:'black'
		});
	});
</script>
</body>

errorClass

Custom CSS class for validation errors.

validClass

Custom CSS class to mark a field validated.

errorAttribute

An html attribute that stores the ID of the error message container for this element. It's set to data-h5-errorid by default. Note: The data- attribute prefix is a new feature of HTML5, used to store an element's meta-data.

E.g: <input id="name" data-h5-errorid="nameError" required >

kbSelectors

A list of CSS selectors for attaching keyboard-oriented events.

Default: kbSelectors: ':text, :password, select, textarea'

focusout, focusin, change, keyup

A list of CSS selectors for attaching "mouse oriented" events.

Default: mSelectors: ':radio, :checkbox, select, option'

click

(Event) The only default mouse-oriented event. Since it probably makes little sense to trigger validation on other mouse events, I'll leave it to you to figure out how to enable them.

Note: The click event isn't just for the mouse. It will trigger for keyboard and touch screen interactions, too.

click: true

6. Event API

h5Validate supports the following events:

instance

Instance created.

validated

The element in question has been validated. A validity object is passed into the event handler containing:

{
	element: HTMLObject, // A reference to the validated element
	customError: Bool, // Custom validity failed.
	patternMismatch: Bool, // Input does not match pattern
	rangeOverflow: Bool, // Input is greater than max attribute value
	rangeUnderflow: Bool, // Input is less than min attribute value
	stepMismatch: Bool, // Input does not conform to the step attribute setting
	tooLong: Bool, // Input is too long
	typeMismatch: Bool, // Wrong input type
	valid: Bool, // Input is valid
	valueMissing: Bool // Required value is missing
}

formValidated

The form in question has been validated. An object is passed with an object containing a bool, valid, and an array of validity objects corresponding to the validated elements.

7. Methods

$.h5Validate.addPatterns(patterns)

Take a map of pattern names and HTML5-compatible regular expressions, and add them to the patternLibrary. Patterns in the library are automatically assigned to HTML element pattern attributes for validation.

{object} patterns A map of pattern names and HTML5 compatible regular expressions.

E.g.:

<input class="h5-phone" id="phone" name="phone" type="text" placeholder="555-555-5555" title="555-555-5555" />

The class="h5-phone" bit is the part doing the magic. The h5- prefix tells you that this class is a handle that we can use to attach validation rules to. Internally, we just tack this prefix to the front of the pattern names to get the right selectors.

In your JavaScript, specify the pattern name without the class prefix. Keeping the prefix off lets us easily share and re-use pattern libraries between projects.

$(document).ready(function () {
	$.h5Validate.addPatterns({
		phone: /([\+][0-9]{1,3}([ \.\-])?)?([\(]{1}[0-9]{3}[\)])?([0-9A-Z \.\-]{1,32})((x|ext|extension)?[0-9]{1,4}?)/				
	});

	$(form).h5Validate();
});

$.h5Validate.validValues(selector, values)

Take a valid jQuery selector, and a list of valid values to validate against. If the user input isn't in the list, validation fails.

{String} selector Any valid jQuery selector.

{Array} values A list of valid values to validate selected fields against.

8. New input types


Warning: Each browser has its own way of treating these new input types. iOS might swap out the on-screen keyboard (cool!), while Chrome renders custom UI controls that don't always make sense (like up and down arrows for datetime inputs.)

What's worse, some of the styles that get applied to these elements are browser-specific, and ignore CSS cascading -- so before you can add your own look and feel, you first have to turn off each native browser's look and feel. For example, h5Validate works just fine on that search field down there, but in Chrome, it ignores our CSS because you first have to turn off -webkit-appearance: searchfield; before you style it. (Hint: You may want to search for a good HTML5 CSS reset).


h5Validate does not currently validate new element types automatically. The pattern and required attributes work fine, but h5Validate will not automatically apply email validation to fields with type="email", etc.. (Yet.)

Here are the HTML5 input types:

<form>
    <div><input title="normal" required></div>
    <div><input type="tel" required></div>
    <div><input type="search" required></div>
    <div><input type="email" required></div>
    <div><input type="url" required></div>
    <div><input type="datetime" required></div>
    <div><input type="date" required></div>
    <div><input type="month" required></div>
    <div><input type="week" required></div>
    <div><input type="time" required></div>
    <div><input type="datetime-local" required></div>
    <div><input type="number" required></div>
    <div><input type="range" required></div>
    <div><input type="color" required></div>
</form>
Comments
  • Cannot get a simple example to work

    Cannot get a simple example to work

    I've downloaded the latest release from Github and I'm trying a very simple example, but I can't get it to work:

    
    <!DOCTYPE HTML>
    <html>
      <head>
      </head>
      <body>
          <form id="settings-form" action="someotherpage.html">
            <input type="text" required/>
            <input type="submit"/>
          </form>
          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
          <script src="jquery.h5validate.js"></script>
    
            <script>
            $(document).ready(function () {
                $('form').h5Validate();
            });
            </script>
      </body>
    </html>
    
    As soon as I use h5Validate() the standard HTML5 validation of the browser (chrome) stops working
    and the page submits even if the text field is empty.
    
    I'm obviously doing something wrong, any suggestions?
    
    The JavaScript console show no errors.
    
    opened by timothyparez 21
  • Public validation method

    Public validation method

    Hi! It would be good having a public validation method that you can trigger. Now i have to loop the elements and trigger the event manually to make it validate which is quite hacky.

    It would be great to have some sort of method to validate whenever you want. This way I could easily validate when the page loads, and on submit for instance.

    Also it would be good to have some way to check if a form is valid or not.

    opened by danielmahal 17
  • Use with AJAX Form Submission

    Use with AJAX Form Submission

    It would be nice to see an example of how this plugin can be used when you want to validate a form prior to performing an AJAX form submission (i.e. not doing a submit). The only way I get this to remotely work is to do the following:

    1. Enter all field values first
    2. Then call the $('#myform').h5Validate() upon the "checkout" button click
    3. Then call if ($('#myform').h5Validate('allValid')) { ... }

    If I try to first call the $('#myform').h5Validate() upon form initialization then call the 'allValid' upon checkout button click...the 'allValid' call seems to work but it does not implement the default invalid CSS for the invalid fields.

    What am I doing wrong here?

    opened by ghost 13
  • Extended phone regex - see below

    Extended phone regex - see below

    Added ^ and $ for start and end so surplus chars cause an error Extended the numbers allowed in brackets to be 6 so (01224) is allowed Added the optional space so ext 5555 is allowed as well as ext5555 Made the whole thing case insensitive to allow for EXTENSION, etc

    opened by u01jmg3 10
  • Make rewriting of errror message texts by element title attribute optional.

    Make rewriting of errror message texts by element title attribute optional.

    I would really like if the error message text is the error message text and that it does not get rewritten because I may have a title attribute on my element. Semantically they may not have to have the same value or meaning. The offending code is in the markInvalid() method.

    opened by dbroz 9
  • Validate select element, does not seem to work?

    Validate select element, does not seem to work?

    Hi,

    I'm trying to validate required on a select element, h5 seem to ignore it, this always returns true: $('#BillingCountry').h5Validate('allValid'); (The element is visible)

    <select type="select" name="BillingCountry" id="BillingCountry" required="required">
                              <option>-- Choose Country --</option>
                              <optgroup label="Europe">
                              <option value="SE">Sweden</option>
                              <option value="AX">Aland islands</option>
                              <option value="DK">Denmark</option>
                              <option value="FI">Finland</option>
                              <option value="NO">Norway</option>
                              </optgroup>
    </select>
    

    EDIT: Solved by setting to value="". I think this should be a little more flexible, some CMS'es use value="-1" or no value attribute at all.

    opened by tmikaeld 9
  • Use data-attribute instead or as alternative to class

    Use data-attribute instead or as alternative to class

    it would be great, if we could use the HTML5-data-attribute to specify the validation-pattern.

    e.g. data-h5="phone" instead of class="h5-phone"

    opened by tobaco 9
  • Noob

    Noob

    Fairly sure this is the wrong place to ask for help but... I have a select drop down that toggles 'invalid/red' on click and stays red until a value is selected. The default 'select one..." value= '' and has attribute required="required". I need the 'select' inputs to only validate on form submission. I believe robust examples of the event API would lead me to a solution. However, I cannot find advanced examples (only the basic stuff on the 'home page'). Short of reading/learning the raw code, is there someplace I can retrieve advanced information?

    Thx Hoss.

    opened by hcshoss 8
  • Validating hidden elements, overriding not working.

    Validating hidden elements, overriding not working.

    Hi,

    I'm having trouble overriding the :visible setting, since i need to validate a hidden select element.

    Setting a new setting to:

    
    

    Does not work.

    Setting a new setting to:

    Does not work.

    Changing the default code to:

    
    

    Works.

    A better way to override this without changing the plugin code would be great.

    opened by tmikaeld 7
  • errorClass different element

    errorClass different element

    Sometimes you want to add an errorClass to an element that's around your label and inputs. This way you can change the color from your labels etc...

    That would be a nice feature.

    opened by IschaGast 7
  • Problem when using allValid

    Problem when using allValid

    Hey,

    Your library is absolutely perfect :)

    I understand you're a bit busy, but could you help a bit. I'm trying to validate a form and then get the result.

    //Validate Contact Form
    $('#js-contact-form').submit( function( event ) {
        var result = $('#js-contact-form').h5Validate('allValid');
        if ( result == true ) {
            // Do stuff here
        }
    

    }

    The error I get:

     [Error] TypeError: 'undefined' is not an object (evaluating 'settings[action]')
     h5Validate (jquery-h5validate.min.js, line 1)
     (anonymous function) (main.js, line 183)
     dispatch (jquery.min.js, line 3)
     handle (jquery.min.js, line 3)
    

    jQuery 2.1

    opened by zenopopovici 6
  • Long form, scroll to error?

    Long form, scroll to error?

    I'm very much a JS noob. I have the validation working, and I love the idea of this project - basically make the browser act like it truly supports html5 validation. :)

    I have a very long form, that even on an iPad has form items out of view when hitting "submit". Is there a simple way to have the browser scroll up to where the first error exists?

    opened by sporkman 1
  • Make this compatible with Browserify and npm

    Make this compatible with Browserify and npm

    • [ ] Inject jQuery dependency into a factory function that constructs the h5Validate plugin. This way, users can swap out jQuery with anything that features a compatible API.
    • [ ] Publish to npm
    opened by ericelliott 1
  • No

    No "min" validation in Safari

    When i activate h5validate in my script, and have an input field with a "min" attribute, it get submitted anyway (only in Safari).

    Demonstration: http://jsfiddle.net/wjZT2/3/

    opened by gruberb 1
Owner
Eric Elliott
Eric Elliott is the author of "Composing Software". He has contributed to software experiences for Adobe, Zumba, BBC, Usher, etc.
Eric Elliott
FieldVal - multipurpose validation library. Supports both sync and async validation.

FieldVal-JS The FieldVal-JS library allows you to easily validate data and provide readable and structured error reports. Documentation and Examples D

null 137 Sep 24, 2022
Cross Browser HTML5 Form Validation.

Validatr Cross Browser HTML5 Form Validation. Getting Started View the documentation to learn how to use Validatr. Changelog Version 0.5.1 - 2013-03-1

Jay Morrow 279 Nov 1, 2022
jQuery form validation plugin

jQuery.validationEngine v3.1.0 Looking for official contributors This project has now been going on for more than 7 years, right now I only maintain t

Cedric Dugas 2.6k Dec 23, 2022
HTML 5 & Bootstrap Jquery Form Validation Plugin

HTML 5 & Bootstrap Jquery Form Validation Plugin HTML 5 & Bootstrap 5 & Jquery 3 jbvalidator is a fresh new jQuery based form validation plugin that i

null 37 Dec 6, 2022
Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

upjs 314 Dec 26, 2022
This Login Form made using React hooks , React Js , Css, Json. This form have 3 inputs, it also validate those inputs & it also having length limitations.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Yogesh Sharma 0 Jan 3, 2022
Jquery-anyimagecomparisonslider-plugin - The any Image Comparison Slider is an extremely versatile yet slim slider for comparing images. You have a lot of options to configure the slider and it works just about everywhere.

any Image Comparison Slider (jquery-anyimagecomparisonslider-plugin ) Description The any Image Comparison Slider is an extremely versatile yet slim s

Niklas 6 Sep 12, 2022
Lightweight and powerfull library for declarative form validation

Formurai is a lightweight and powerfull library for declarative form validation Features Setup Usage Options Methods Rules Examples Roadmap Features ?

Illia 49 May 13, 2022
Lightweight JavaScript form validation library inspired by CodeIgniter.

validate.js validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. Features Validate form fields from over a dozen r

Rick Harrison 2.6k Dec 15, 2022
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
This is Example of how to use the React Hook Form

Getting Started with my-reacthook-form You can get this project by running git clone https://github.com/ivandi1980/my-reacthook-form.git Available Scr

ivandjoh 3 Apr 4, 2022
JQuery-TableToExcel - Light weight jQuery plugin for export HTML table to excel file

tableToExcel Light weight jQuery plugin for export table to excel file Demos Website and demo here: http://tanvirpro.com/all_project/jQueryTableToExce

Tanvir Sarker 4 May 8, 2022
Jquery.iocurve - jQuery plugin like Tone Curve on Photoshop or GIMP

jquery.iocurve jQuery plugin like Tone Curve on Photoshop or GIMP. See Official page for more information. Quick start Create HTML and open in your br

null 5 Jul 28, 2022
A simple environment variables validator for Node.js and web browsers

A simple environment variables validator for Node.js and web browsers

Mathieu Acthernoene 25 Jul 20, 2022
Jquery.Circle.js - Circle is a Javascript global-menu library for jQuery.

Circle About Circle is a Javascript global-menu library for jQuery. Read more at the website: http://uc.gpgkd906.com/ Installation Just include the Ja

陈瀚 3 Jul 19, 2021
Simple and basic javascript form validations

JavaScript-Form-Validations Simple and basic javascript form validations Table of Validations: S. No. Type of validation Link 1 Non-empty text field h

MAINAK CHAUDHURI 23 Dec 17, 2022