Git Product home page Git Product logo

ericelliott / h5validate Goto Github PK

View Code? Open in Web Editor NEW
576.0 22.0 125.0 292 KB

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.

JavaScript 67.57% Shell 0.04% CSS 8.80% HTML 23.58%

h5validate's Introduction

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>

h5validate's People

Contributors

ericelliott avatar joelpurra avatar opendining avatar paulcichonski avatar sjoerdmulder avatar szepeviktor avatar u01jmg3 avatar wbinnssmith avatar zenopopovici avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

h5validate's Issues

Having an issue getting the validation to work in a rails form submit action

I tried all on this page / thread and it did not seem to work. I get this
TypeError: settings is undefined
[Break On This Error]

return settings[action].apply(this, args);

and nothing shows as being validated and is not highlighted. But when I add the h5validate on just the document.ready() it validates but does not keep the focus in the field. How can I use to set the field focus to the validated field.

onsubmit is always executed.

If I run this on chrome, I get the alert ONLY when there is a value in the required field.





If I use h5Validate, I always see the alert. That's not consistent. In my opinion, the alert message should be shown only if the form is valid (like it happens in Chrome)

Support for placeholder attribute

Any chance you would be willing to add support for the placeholder attribute? I mean so that it works in older browsers. Seems like using h5validate together with a placeholder plugin will probably fail.

Or perhaps point me in the right direction towards adding support myself?

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.

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?

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.

h5Validate Needs a Refresh

Implement missing features as described here:
http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/

Add support for email type, at minimum (very handy for mobile).

Take a fresh look at new input types (Specifically, can we disable the horrible default browser UI for number types? Can we make it easy for users to override built-in browser date pickers, etc...?) Sadly, the spec leaves a lot of those implementation decisions to the browser, without specifying standard ways to override them or style them, but we might be able to track down all the browser implementations.

I'm open to help with these things. I'm not sure when I'll find time.

Support for required dropdowns

Something like

Select Something Foo selection

I think all you need is this line of code:

settings.delegateEvents('select[required]', {change: true}, this, settings);

Not sure if such use of required attribute is in html5 spec though. Could be made optional.

a test suite

this project really really needs a test suite.

as forms are a delicate area, we need robust testing around them

there is probably some tests in the w3c html5 suite and definitely in webkit layouttests that could get you started.

you could also gank tests from h5f and webshim

Cross browser support for maxlength on textarea

I haven't been able to figure out how to get h5Validate to validate maxlength on textarea elements. I see the validity.tooLong attribute but not sure how it gets triggered in IE8/9. Is it supported?

Chosen.js validate

I want make validation for chosen.js block
I add css
.chzn-select{
display: block !important;
position: absolute;
left: -9999px;
}
Validation for select work,
but how can i add error class for chosen block

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 -- Choose Country -- to value="". I think this should be a little more flexible, some CMS'es use value="-1" or no value attribute at all.

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.

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

I resubmit this issue as I believe it was closed prematurely.
The argument given against it was the HTML5 spec recommends the title attribute is used for storing the error message.

But after reading the spec (Please read the spec):
http://www.w3.org/TR/html5/common-input-element-attributes.html#attr-input-pattern

The spec does not make such a recommendation, it suggests that the title attribute must be used for storing pattern descriptions if the pattern attribute is present, and does not stipulate it's use for error messages. In fact it even suggests that the title attribute text should not allude to any error at all, however additions can be made to improve usability. So I believe making the title attribute as a error message store should be optional and definitely hookable to support additional messages. The HTML5 spec clearly supports this.

Not validating a field?

Hi again :-)

I'm trying to make h5 not validate specific fields in a form.

Yet using :not() or .not() does not work. Is there any other way i can make h5 ignore specific fields?

Maxlength -1 in FF 16.0.2

FF reports maxlength as -1 if not set, so h5Validate always reports "tooLong" in lines 279-282 , even with the field empty.

To fix this, I changed the if to:

                if (!isNaN(maxlength) && maxlength >= 0 && value.length > maxlength) {

Issues with 'required' attribute

First off, I'm aware that in the HTML5 spec, it stats that if the 'required' attribute is specified on an , a value is required, regardless of value the value of 'required' actually is (eq. still means that it is required.

It would appear that some browser's DOM (Chrome and FF) is automatically inserting a property on the HTMLInputElement object named 'required' with a value of false. As such, the logic for a required value in your plugin get executed regardless of whether or not the markup specifies that the element is required.

I'd like to suggest that since your plugin does not have to conform to the spec, you also check for a "false" value.

h5-phone class not causing correct phone validation

Using v0.80

<input type="text" maxlength="15" class="h5-phone" id="phone">

If I enter, say, 121212 and check $('#phone').h5Validate('isValid') it returns true. Same thing whether type is text or tel.

I saw the older ticket (#13) and your comment there that the phone regex is fairly generous. Maybe we need additional pattern/classes like h5-usphone to handle tighter requirements?

keyup validation

I'm hoping to setup a validation check on each character entered into an input or textarea.

I'm getting very close simply by setting the keyup option true, but I'm getting unwanted validation when the tab (or other) key is used to enter a field.

Can you suggest a way to suppress validation on key up unless a character has been entered?

I tried the change option, but that only validates input and textarea on focusout. I'm looking for validation on each character entered.

Thanks for the great plugin, it's really nice to have an updated validate plugin.

suggestion, stick to validation only

Hi,

IMHO validation and showing/hiding errors, adding css classes etc are separate things. When combined in one library, you lose flexibility. I think it would be better to just do validation and offer callback functions to the developer implementing the library. That way he/she can define exactly what will happen when elements enter different validation states.

You can of course offer the functionality is it exists right now as seperate plugin.

Just my two cents!

readOnly attribute

Problem:
readOnly attributes get validated

Expected:
According to the HTML5 spec: "If the readonly attribute is specified on an input element, the element is barred from constraint validation."

Capital letter

Having problem with the plugin, when i start the text with capital letter then h5validate still tells that its invalid.
http://grab.by/8vzr

EDIT: Similar problem with email regex pattern. Ex: [email protected] is considered invalid.

Should make the patterns case insensiteve.

how can i validate against remotes

say i have a json interface /user/isTaken/:id how can i validate the username field in a form against this remote to ensure that the username the user has chosen is unique?

Support for multipart forms?

It would be great if this plugin could support multipart forms, for example validating a div with fields at a time.

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.

Add support for formnovalidate and novalidate

This attribute is useful to include "save" buttons on forms that have validation constraints, to allow users to save their progress even though they haven't fully entered the data in the form. The following example shows a simple form that has two required fields. There are three buttons: one to submit the form, which requires both fields to be filled in; one to save the form so that the user can come back and fill it in later; and one to cancel the form altogether.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.