Overview

vForm is a form validation library based on the HTML 5 standards.

Disable the browser default errors

Modern browsers show buil-in error styles for invalid fields, to disable that make sure to add novalidate="novalidate" attribute to the <form> tag.

Install

Get vForm Fork on GitHub

Optionally, you can install vForm with bower:

$ bower install vform


Or download the production version / development version

Requirements

vForm is working best with jQuery 2.x, however it can work well with older version of jQuery as well 1.11.x
if you're using an older version - you can run the unit test.

Including files

<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="vform.min.js"></script>

How to use it

$('#my-form').vForm(function( event ){
    return event.data.form.validate();
});

Compatibility

vForm is fully functional on all modern browsers, as well as some old ones such as Internet Explorer 8+. It is also designed to work on touch devices such as mobile phones or tablets.

Validations

Required Fields

To validate the field has a value add a required attribute.

<input type="text" required>
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Required Group

You can create a required group to validate that at least one of the fields is not blank, to do that add data-group="group-name" to each of the fields, (you can have multiple groups if you'd like) make sure they have the required attrebute as well.

Please enter at least one contact method:

<input type="text" data-group="group-name" required>
<input type="text" data-group="group-name" required>
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

String

Usefull to validate chars legth, you can use the min and max attributes. Note that string validation is only avalible for those HTML5 types: text, password, email, url, search, tel, and textarea.

<input type="text" min="3"> <!-- Minimum 3 characters -->
<input type="text" max="7"> <!-- Maximum 7 characters -->
<input type="text" min="4" max="8"> <!-- Between 4 to 8 characters -->
<input type="text" min="5" max="5"> <!-- Exactly 5 characters -->
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Numeric

Validating a numeric value is only avalible for those HTML5 types: month, week, number and range.

<input type="number" min="11"> <!-- Greater than 10 -->
<input type="number" max="20"> <!-- Less than 20 -->
<input type="range" min="1" max="100" data-min="30" data-max="70"> <!-- Between 30 to 70 characters -->
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Email

To validate an email field just make sure that type="email". You can also add a pattern attribute to specify a custom regex pattern. Note that blank will be valid without the required attribute.

<input type="email" required>
<input type="email" pattern="\S+@\S+" required> <!-- Use custom pattern -->
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

URL

To validate a URL field just make sure that type="url". You can also add a pattern attribute to specify a custom regex pattern. Note that blank will be valid without the required attribute.

<input type="url">
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

IP Address

To validate a IP address (v4 only) field just add data-validate="ip". Validating IP address is only avalible for text & url input types. You can also add a pattern attribute to specify a custom regex pattern. Note that blank will be valid without the required attribute.

<input type="url" data-validate="ip">
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Credit Card

To validate a crecit card number you'll need to add data-validate="credit-card" and make sure to use text or number input types. vForm support those credit cards: Visa, MasterCard, Discover, American Express, Diners Club, JCB. Note that blank will be valid without the required attribute.

<input type="text" data-validate="credit-card">
<input type="number" min="99" max="999">
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Local validation only!

vForm will only validate the credit card localy, it dose not confirm the correct validity of the credit card information with a bank or any 3rd party authority.

Color

To validate a color field just make sure that type="color". You can also add a pattern attribute to specify a custom regex pattern. Note that blank will be valid without the required attribute.

<input type="color">
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Patterns

To validate a regex pattern just use the pattern attribute. Note that blank will be valid without the required attribute.

<input type="text" pattern="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}">
<!-- Phone number that match the pattern: "(123) 456-7890" -->
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Password

You can use the min or pattern attribute to validate the password, and data-match attribute to validation the password confirmation. Note that data-match should contain the original password field id.

<input type="password" id="password-field" required>
<input type="password" data-match="password-field">
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Checkboxes

Checkbox can be validated individually or by group, for group validation wrap with <fieldset> and use the min & max attributes. Note that you can't add required attribute to the <fieldset>, use min="1" instead.

<input type="checkbox" required> <!-- Required checkbox -->

<!-- Checkbox group -->
<fieldset min="2" max="3">
    <label>
        <input type="checkbox">
        Group option one
    </label>
    <label>
        <input type="checkbox">
        Group option two
    </label>
    <label>
        <input type="checkbox">
        Group option three
    </label>
    <label>
        <input type="checkbox">
        Group option four
    </label>
</fieldset>
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Keep checkboxes & radio separated

Make sure to separate checkboxes & radio buttons into different <fieldset> tags.

Radio Buttons

Radios can be validated only by group, for that wrap them with <fieldset>, you can only add required attribute to this <fieldset>.

<fieldset required>
    <label>
        <input type="radio" name="example">
        Option one
    </label>
    <label>
        <input type="radio" name="example">
        Option two
    </label>
    <label>
        <input type="radio" name="example">
        Option three
    </label>
</fieldset>
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Better way to validate radio buttons

Since radio buttons cannot be unselected, you can just add checked attribute to one of them. So there's no need to actually validate them.

Cross-browser compatibility

While Form.js will ignore those items in all browsers, Internet Explorer 11 and below don't fully support the disabled attribute on a <fieldset>. Use custom JavaScript to disable the fieldset in these browsers.

Ignored

Disabled fields are being ignored, however you can also add data-ignore="true" to manually ignore fields from being validated.

<input type="text" disabled>
<input type="text" data-ignore="true" required>
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Errors

Error Messages

You can specify the error messages from the configuration as default or from the markup to apply individually.
The error messages are based on the validation type as specified.

Validation Type Option Key Marktup Attribute Default Value
Default default data-error-msg Invalid
Required required data-required-error-msg None
Required Group required_group data-required-group-error-msg None
String Minimun Length min_length data-min-error-msg None
String Maximum Length max_length data-max-error-msg None
Numeric Minimun Value min data-min-error-msg None
Numeric Maximum Value max data-max-error-msg None
Email email data-email-error-msg None
URL url data-url-error-msg None
IP Address ip data-ip-error-msg None
Credit Card credit data-cc-error-msg None
Color color data-color-error-msg None
Pattern pattern data-pattern-error-msg None
Password Match match data-match-error-msg None
Checkboxes Minimun Selection min_selection data-min-error-msg None
Checkboxes Maximum Selection max_selection data-max-error-msg None
<input type="text" placeholder="First Name" min="3" required data-required-error-msg="Enter first name" data-min-error-msg="At least 3 characters">
<input type="email" placeholder="Email" required data-required-error-msg="Required email" data-email-error-msg="Email is invalid">
<label>
    <input type="checkbox" reruired data-required-error-msg="Don't forget to check this">
    Must check this
</label>
var form = $('form').vForm(function(){
    form.validate();
    return false;
});

Summarized Errors

Summarized errors are gathered together and can be shown above the form.

<div id=">"></div>

<input type="text" placeholder="Name" required data-required-error-msg="Please enter the name">
<input type="text" placeholder="Phone: (123) 456-7890" pattern="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}" data-pattern-error-msg="Phone number is incorrect">
<input type="email" placeholder="Email" required data-required-error-msg="Please enter the email" data-email-error-msg="Email is invalid">
<input type="url" placeholder="http://" data-url-error-msg="URL address is invalid">
<fieldset required data-required-error-msg="Please select the gender">
    <label>
        <input type="radio" name="example">
        Male
    </label>
    <label>
        <input type="radio" name="example">
        Female
    </label>
</fieldset>
var form = $('form').vForm({
    onBegin: function(fields){
        $('#form-errors').html('').hide();
        return true;
    },
    onFail: function(fields, messages){
        var $container = $('#form-errors'),
            html = '';

        if(messages.length){
            html = '<div class="container"><h5>Please resolve those errors:</h5><ul>';
            $.each(messages, function(index, message){ html += '<li>' + message + '</li>'; });
            html += '</ul></div>';
            $container.html(html).show();
        }

        return false;
    }
}, function(){
    form.validate();
    return false;
});

i18n

vForm can easily support any language for the error message.

<select id="lang">
    <option value="en">English</option>
    <option value="es">Español</option>
    <option value="ru">Русский</option>
    <option value="it">Italiano</option>
    <option value="de">Deutsch</option>
    <option value="fr">Français</option>
    <option value="jp">日本語</option>
    <option value="he">עברית</option>
</select>

<input type="text" name="name" required>
<input type="email" name="email" required>
<textarea name="message" required></textarea>
var data = {
    en: {
        default: 'Invalid',
        required: 'Required',
        email: 'Incorrect Email',
        message: 'Enter Message'
    },
    es: {
        default: 'Inválido',
        required: 'Necesario',
        email: 'Correo electrónico incorrecta',
        message: 'Introduzca Mensaje'
    },
    ru: {
        default: 'Неверно',
        required: 'Tребуется',
        email: 'Неправильное Email',
        message: 'Введите Cообщение'
    },
    it: {
        default: 'Non valido',
        required: 'Necessario',
        email: 'Errata Email',
        message: 'Inserisci Messaggio'
    },
    de: {
        default: 'Ungültig',
        required: 'Erforderlich',
        email: 'Falsche E-Mail Adresse',
        message: 'Geben Sie Nachricht'
    },
    fr: {
        default: 'Invalide',
        required: 'Requis',
        email: 'Adresse électronique incorrecte',
        message: 'Entrez Message'
    },
    jp: {
        default: '無効',
        required: '必須',
        email: 'メールアドレスが正しくありません',
        message: 'メッセージを入力してください'
    },
    he: {
        default: 'לא תקין',
        required: 'חובה',
        email: 'דוא״ל לא תקין',
        message: 'יש להזין הודעה'
    }
}

var form = $('form').vForm({
    onErrorMessage: function($field, message, key){
        if($field.is('textarea') && key === 'required'){ key = 'message'; }
        var lang = $('#lang').val();
        return data[lang][key];
    }
}, function(e){
    form.validate();
    return false;
});

Live Validation

Live validation will show only the errors before sublimting the form, you can enable live validation on change, keyup and blur events.

<select id="event" data-ignore="true">
    <option value="change">on Change</option>
    <option value="keyup">on Key Up</option>
    <option value="blur" selected>on Blur</option>
</select>

<input type="text" placeholder="Name" required>
<input type="email" placeholder="Email" required>
<input type="number" placeholder="Number (between 10 and 20)" min="11" max="20">

Single Field Validation

form.validate( $('#my-field') );

// OR

form.validate('#my-field');

Processing

Form Submition

$('#my-form').vForm(function( event ){
    return event.data.form.validate();
});

Ajax

var form = $('#my-form').vForm(function(){

    if( form.validate() ){
        $.post('test.php', $(this).serialize(), function(){
            alert( "Done!" );
        });
    }

    return false;
});

Form submit event must return false

If you forget (or return true) on the form submit event, the form will be submitted to itself, means the page will be reloaded.

Events

onBegin ( fields )

Fired Every time the validation process begines.
Params fields Array of all fields that's about to get processed.
Return Boolean whether to proceed with the validation. False will fail the form validation.
Example
function( fields ){
    return true;
}

onBefore ( $field )

Fired Before processing each field.
Params $field jQuery Object of the field.
Return Boolean whether to proceed with the validation. False will skip to the next field.
Example
function( $field ){
    return true;
}

onAfter ( $field, status )

Fired After processing each field.
Params $field jQuery Object of the field.
status Boolean the validation status of the field.
Return Boolean whether this field is valid.
Example
function( $field, status ){
    return status;
}

onFail ( fields, messages )

Fired When the form validation fails after processing all of the fields.
Params fields Array of all invalid fields.
messages Array of all the error messages.
Return Boolean whether ths form is valid.
Example
function( fields, messages ){
    return false;
}

onSuccess ( fields )

Fired When the form is validated after processing all of the fields.
Params fields Array of all fields that was processed.
Return Boolean whether ths form is valid.
Example
function( fields ){
    return true;
}

onErrorMessage ( $field, message, key )

Fired When field is invalid and need to show an error message.
Params $field jQuery Object of the field.
message String error message.
key String error key as described at the error messages.
Return String the HTML code for the error message.
Example
function( $field, message, key ){
    return "<span class='error-message'>" + message + "</span>";
}

onValidFeedback ( $field )

Fired When field is valid and need to show a valid feedback.
Params $field jQuery Object of the field.
Return String the HTML code for the valid feedback.
Example
function( $field ){
    return "<span class='valid-feedback'>Valid</span>";
}

Options

Key Default Value Data Type Description
fields "input, textarea, select" String Selector for the fields that should be validated.
trim True Boolean If true, each field will get trimed before processing the validation.
html False Boolean If true, will allow HTML tags, other wise will esace HTML before validation.
focus False Boolean If true, will set the focus on the first invalid field after processing.
live "" String Avalible options are: "onKeyUp", "onBlur", "onChnage".
error. enabled True Boolean If true, will show error messages.
messages { default: "Invalid" } Object See Error Messages for object documentation.
feedback False Boolean If true, will show field valid feedback.
{
    fields: "input, textarea, select",
    trim: true,
    html: false,
    focus: false,
    live: false,
    error: {
        enabled: false,
        messages: { default: "Invalid" },
    },
    feedback: false,

    // Events
    onBegin: function( fields ){ return true; },
    onBefore: function( $field ){ return true; },
    onAfter: function( $field, status ){ return status; },
    onFail: function( fields, messages ){ return false; },
    onSuccess: function( fields ){ return true; },
    onErrorMessage: function( $field, message ){ return "" + message + ""; },
    onValidFeedback: function( $field ){  return "Valid"; }
}

Methods

You'll have to ceate a variable and store the form object in order to call the methods.

Create ( options [, onSubmit ] )

Form is highly configurable library. Features can be enabled, disabled or customised to meet your exact needs for your form implementation. Customisation of these options are performed by defining options in the constructor, see all options list.

The native way:
var myForm = new form({
    feedback: true,
    live: 'keyup'
});
The jQuery way:
var myForm = $('form').vForm({
    feedback: true,
    live: 'keyup'
});

jQuery form method won't return a jQuery object

Using the jQuery short method will return the form element rather than jQuery, so you won't be able to call other jQuery methods. If you need to make sure to call the form function at the end.

Validate ( [options] )

Description Validates the form, you should call this method manually to validate the form.
Params options ( Optional ) Object of all the customized options, see full options list.
Return Boolean whether the form is valid.
Example
myForm.validate( options );

Status ( )

Description Returns the tatus of the form.
Return Boolean whether the form is valid.
Example
myForm.status();

Add ( [$field ,] handler [, error] )

Description Adding a custom validation handler.
Params $field ( Optional ) jQuery Object of the field, this will apply the validation only for this field.
handler Function that will be fired as part the validation process stack.
error ( Optional ) String of error message that will be used if invalid.
Return Boolean whether the validation handler added successfully.
Handler Params value of the field.
$field jQuery Object of the field.
Handler Return Boolean whether the field is valid.
myForm.add(function( value ){
    return ( value === 'Ben' ) ? true : false ;
}, 'Value is not Ben');

Get ( [filter] )

Description Get all the form fields.
Params filter ( Optional ) String avalible options are: "all", "valid", "invalid" & "errors".
Return Array of jQuery Object of the fields.
Example
myForm.get('invalid');

Set ( key, value )

Description Updating the form options (see full options list).
Params key String the option key.
value the option value.
Example
myForm.set('focus',true);

Clear ( )

Reset all the form fields, for default values use data-default attribute.

$('#btn-reset').on('click', function(){
    myForm.clear();
});

License MIT

Copyright (c) 2016 Michael Shapiro

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.