Parsley.js Documentation & API

### Parsley.js

## Demonstration

Classy demo | HTML Code (yes, no JS !)
--- | ---

Full Name * : Email * : Website : Message (20 chars min, 200 max) :
Please, note that this demo form is not a perfect example of UX-awareness. The aim here is to show a quick overview of data-API and Parsley customizable behavior.

    <form id="demo-form" data-validate="parsley">
        <label for="fullname">Full Name * :</label>
        <input type="text" id="fullname" name="fullname" data-required="true" />

        <label for="email">Email * :</label>
        <input type="text" id="email" name="email" data-trigger="change" data-required="true" data-type="email" />

        <label for="website">Website :</label>
        <input type="text" id="website" name="website" data-trigger="change" data-type="url" />

        <label for="message">Message (20 chars min, 200 max) :</label>
        <textarea id="message" name="message" data-trigger="keyup" data-rangelength="[20,200]"></textarea>
    </form>

Heads up! Le #UX touch:

- Min char validation: Parsley by default does not proceed with field validation when less than 3 chars have been input. Do not assault your users with error messages too soon! (this behavior is configurable).
- Quick error removal: when a field is detected and shown as invalid, further checks are done on each keypress to try to quickly remove error messages once the field is ok.
- Control focusing on error: on form submission, the first error field is focused to allow the user to easily start fixing errors. (this behavior is configurable)

## Documentation

1. Installation & usage: one or two inclusions!
2. Parsley Form: add some Parsley validation to your forms!
3. Parsley Field: customize each validated field validation behavior
4. Validators: learn the various validations you could do with Parsley
   1. Basic constraints
   2. Type constraints
   3. Extra constraints
5. Javascript: yes, you still can do some javascript with Parsley. Intermediate level only!
   1. General
   2. Form
   3. Fields
6. Parsley CSS: last but not least, Parsley CSS classes
7. Plugins & Localization: extend Parsley messages, validators, templates and more!
8. Integrations: Use parsley from other frameworks.

### Parsley Installation

Just include the Parsley.js file (with jQuery or Zepto with data and fx_methods modules added) or use Parsley standalone (with Zepto bundled inside)

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="parsley.js"></script>

    <form data-validate="parsley">
      [...]
    </form>

Top

### Parsley Form

This is the main Parsley form validation factory, where you decide if a form is validated, and set some extra options.

    <form data-validate="parsley"></form>

Heads up! HTML5: If you use HTML5 validation feature, add: `novalidate` attribute to `form` tag.

#### Properties

Property | Default | Description | Demonstration
--- | --- | --- | ---
`data-validate` |  | Bind Parsley validation to the form and its items with validation constraints |
`data-show-errors` | true | Choose to show or not Parsley error messages & success / errors classes |

`data-focus`

first

Specify which field will be focused first on form validation errors. `first`, `last` and `none` allowed

`data-bind` |  | The attribute data-validate must be used on a form. However, if you want to bind the validation to another DOM element, just add this attribute and set it to `true` |

Top

### Parsley Field

Once your form is validated by Parsley, add validation constraints and various other options.

    <form data-validate="parsley">
        <input type="text" name="email" data-type="email" />
    </form>

#### Properties

Property | Default | Description | Demonstration
--- | --- | --- | ---
`data-trigger` | none | Specify one or many javascript events that will trigger item validation. eg: `data-trigger="change"`. To set multiple events, separate them by a space `data-trigger="focusin focusout"`. See the various events supported by jQuery. |
`data-value` |  | Override the value attribute of a form field. Useful for file inputs, where you're not allowed to set a value. eg: `data-value="uploadedfile.png"` |
`data-validation-minlength` | 3 | Specify how many characters need to be input before the the validation process fires. eg: `data-validation-minlength="4"` |

`data-error-message`

Customize a unique global message for this field. Shown if one constraint fails.
eg:

    data-type="alphanum" data-rangelength="[10,10]"
    data-error-message="You must enter a 10 characters alphanumeric value"

`data-error-container`

Specify here the container where Parsley should set the errors.
eg:

    data-error-container="ul#myproperlabel li.someclass"

`data-`constraintName`-message` `data-type-`type`-message` |  | Customize the error message for the field constraint. eg: `data-minlength-message="Custom minlength message"` `data-type-email-message="Custom email message"` |

Top

### Built-in Validators

Name | API | Description | Demonstration
--- | --- | --- | ---

#### Basic constraints

Required

`data-required="true"`
`class="required"`
HTML5 `required="required"`

Validate that a required field has been filled.

Radio: |

Not Blank

`data-notblank="true"`

Validates that a value is not blank, defined as not equal to a blank string.

Min Length

`data-minlength="6"`

Validates that the length of a string is at least as long as the given limit.

Max Length

`data-maxlength="6"`

Validates that the length of a string is not larger than the given limit.

Range Length

`data-rangelength="[5,10]"`

Validates that a given string length is between some minimum and maximum value.

Min

`data-min="6"`
HTML5 `type="number" min="6"`

Validates that a given number is greater than some minimum number.

Max

`data-max="100"`
HTML5 `type="number" max="100"`

Validates that a given number is less than some maximum number.

Range

`data-range="[6, 100]"`
HTML5 `type="range" min="6" max="100"`

Validates that a given number is between some minimum and maximum number.

RegExp

`data-regexp="<regexp>"`
HTML5 `pattern="regexp"`

Validates that a value matches a specific regular expression. eg: validate a color hexadecimal code: `data-regexp="#[A-Fa-f0-9]{6}"`.
Add a flag to `Regexp()` function: `data-regexp-flag="i"` for example to make regexp case unsensitive

Equal To

`data-equalto="#elem"`

Validates that a value is identical to #elem value. Useful for password repeat validation.

Min check

`data-mincheck="2"`

Validates that a certain minimum number of checkboxes in a group are checked. You can define a group by giving the same name to radio / checkboxes elements or add a `data-group="mygroup"` property to each one of them

Check at least 2 checkboxes: |

Max check

`data-maxcheck="2"`

Validates that a certain maximum number of checkboxes in a group are checked. You can define a group by giving the same name to radio / checkboxes elements or add a `data-group="mygroup"` property to each one of them

Check 2 checkboxes maximum: |

Range check

`data-rangecheck="[1,2]"`

Validates that the number of checked checkboxes in a group is with a certain range. You can define a group by giving the same name to radio / checkboxes elements or add a `data-group="mygroup"` property to each one of them

Check b/w 1&2 checkboxes: |

Remote (Ajax)

`data-remote="http://yoururl.com"`

Custom ajax validation made simple.
`data-remote-method="POST"` to change default `GET` call.
`data-remote-datatype="jsonp"` if you make cross domain ajax call and expect `jsonp`
Parsley will accept these valid returns with a 200 response code: `1`, `true`, `{ "success": "..." }` and assume false otherwise
You can show frontend server-side specific error messages by returning `{ "error": "your custom message" }` or `{ "message": "your custom message" }`

#### Type Constraints

Email

`data-type="email"`
HTML5 `type="email"`

Validates that a value is a valid email address.

Url

`data-type="url"` `type="url"`

Validates that a value is a valid url.

Url strict

`data-type="urlstrict"`

Validates that a value is a valid strict URL, ie: with one of `http`, `https`, `ftp`, `git` allowed protocols.

Digits

`data-type="digits"`

Validates that a value is only digits.

Number

`data-type="number"`
HTML5 `type="number"`

Validates that a value is a valid number.

Alphanum

`data-type="alphanum"`

Validates that a value is a valid alphanumeric string.

Date Iso

`data-type="dateIso"`

Validates that a value is a valid ISO date.

Phone

`data-type="phone"`

Validates that a value is a valid phone number.

#### Extra Validators

There are some extra validators, not shipped along with default Parsley, because they're more specific and less common, and there is no need to add weight to Parsley instead of calling these validators only when needed. Just call `parsley.extend.js` or `dist/parsley.extend.min.js` like this:

    <script type="text/javascript" src="parsley.extend.fr.js"></script>
    <script type="text/javascript" src="parsley.js"></script>

Please, feel free to fork and contribute by adding some useful validators!

##### Here is the list of parsley.extra validators

Name | Api | Description
--- | --- | ---
Min Words | `data-minwords="6"` | Validate that a field has at least 6 words.
Max Words | `data-maxwords="6"` | Validate that a field has 6 words maximum.
Range Words | `data-rangewords="[6,10]"` | Validate that a field has between 6 and 10 words.
Greater Than | `data-greaterthan="#elem"` | Validate that a field's value is greater than #elem's value.
Less Than | `data-lessthan="#elem"` | Validate that a field's value is lower than #elem's value.
Before date | `data-beforedate="#elem"` | Validate that a field's date is before #elem's date.
After date | `data-afterdate="#elem"` | Validate that a field's date is after #elem's date.
In list | `data-inlist="foo, bar, foo bar"` | Validates that a field's value is present within the value list. You can define the delimiter using `data-inlist-delimiter=","`. Delimiter defaults to `","`.
Luhn | `data-luhn="true"` | Validates that a fields value passes the Luhn algorithm. Validates credit card numbers, as well as some other kinds of account numbers.
American Date | `data-americandate="true"` | Validates that a value is a valid American Date. Allows for slash, dot and hyphen delimiters and condensed dates (e.g., M/D/YY MM.DD.YYYY MM-DD-YY).

Top

### Javascript

Parsleys DOM-API is great. But not so great for complex forms, or dynamically generated forms. Learn how to master Parsley javascript style!

Warning : you must remove `data-validate="parsley"` auto-binding code in your forms DOM to allow you to override the default processing and use Parsley purely from javascript.

Method | Returns | Description | Code
--- | --- | --- | ---

#### General

Override default plugin configs

Parsley uses a set of default configs that you can override by passing an object as a parameter when calling Parsley on a form or a field.
Default is:

    {
      // basic data-api overridable properties here..
      inputs: 'input, textarea, select'
      , excluded: 'input[type=hidden]'
      , trigger: false
      , focus: 'first'
      , validationMinlength: 3
      , successClass: 'parsley-success'
      , errorClass: 'parsley-error'
      , validators: {}
      , showErrors: true
      , messages: {}

      //some quite advanced configuration here..
      , validateIfUnchanged: false
      , errors: {                     // specify where parsley error-success classes are set
        classHandler: function ( elem, isRadioOrCheckbox ) {}
      , container: function ( elem, isRadioOrCheckbox ) {}
      , errorsWrapper: '<ul></ul>'
      , errorElem: '<li></li>'
      }
      , listeners: {
          onFieldValidate: function ( elem, ParsleyField ) { return false; }
        , onFormSubmit: function ( isFormValid, event, ParsleyForm ) {}
        , onFieldError: function ( elem, constraints, ParsleyField ) {}
        , onFieldSuccess: function ( elem, constraints, ParsleyField ) {}
      }
    }

Add a custom validator that checks if number is a multiple of another:

    $( '#form' ).parsley( {
        validators: {
          multiple: function ( val, multiple ) {
            return val % multiple === 0;
          }
        }
      , messages: {
          multiple: "This value should be a multiple of %s"
        }
    } );
    <input type="text" data-multiple="3" />

Add a listener

Allows you, even after Parsleys initial form binding, to add a custom listener. Available listeners currently are: `onFieldValidate`, `onFieldError`, `onFieldSuccess` and `onFormSubmit`. Their passed arguments are listed above in Default Plugin config. Note that if onFormSubmit callback returns `false`, form won't be submitted, even if Parsley valid. It allows you to add another custom check on top of Parsley. Similarly, if `onFieldSuccess` returns `false`, field would be considered as invalid and form too.

    $( '#form' ).parsley( 'addListener', {
        onFieldValidate: function ( elem ) {

            // if field is not visible, do not apply Parsley validation!
            if ( !$( elem ).is( ':visible' ) ) {
                return true;
            }

            return false;
        }
    } );

#### Form

Bind Parsley to a form

Useful if your form is dynamically rendered.

    $( '#form' ).parsley();

Validate a form

Boolean

Useful if you want to integrate the form validation process inside custom functions.

    $( '#form' ).parsley( 'validate' );

Test if form valid

Boolean

Useful if you want to integrate the form validation process inside custom functions, without triggering error messages.

    $( '#form' ).parsley( 'isValid' );

Destroy Parsley

Reset error messages, error classes, stop prevent form submission and validation triggered events.

    $( '#form' ).parsley( 'destroy' );

Dynamically add an Item to Form

If an item is dynamically created, it won't be naturally validated with Parsley. Use this to attach it to existing Parsley validated form.

    $( '#form' ).parsley( 'addItem', '#itemid' );

Dynamically remove an Item to Form

If an item is dynamically deleted / removed from form, it will be unfortunately still present in Parsley validation process. Use this to remove it in Parsley form validation process. This field must have an id to be properly destroyed

    $( '#form' ).parsley( 'removeItem', '#itemid' );

#### Field

Validate a field

Boolean

Useful if your want to integrate the field validation process inside custom functions.

    $( '#field' ).parsley( 'validate' );

Add new constraint

Useful if your want to add a constraint to an existing Parsley validated field.

    $( '#field' ).parsley( 'addConstraint', { minlength: 2 } );

Update constraint

Useful if your want to update an existing constraint for a field.

    $( '#field' ).parsley( 'updateConstraint', { minlength: 6 } );

Remove constraint

Useful if your want to remove an existing constraint to an existing Parsley validated field.

    $( '#field' ).parsley( 'removeConstraint', 'minlength' );

More generally, in the Parsley API: All ParsleyForm and ParsleyItem functions can be publicly called using the following syntax:

    $( '#parsleyFormOrFieldId' ).parsley( 'functionName', parameter );

So help yourself, read the code and play with Parsley! ;)
Top

### Parsley CSS

A good #UX goes with a good #UI. Parsley has some base classes you can use to customize things a bit ;) (and of course, rename in the configuration object)

Class | Description
--- | ---
Default classes & templates
`.parsley-validated` | Auto added on each form item that has Parsley validation.
`.parsley-success` | Auto added on each form item that has successfully passed validation.
`.parsley-error` | Auto added on each form item that did not pass Parsley validation.
`ul.parsley-error-list` | Auto added after each form item that did not pass Parsley validation. Container for errors `<li>`.
`li.parsley-error` | Message displayed if constraint failed validation.
Override them!

Change class names

    $('#form').parsley({ successClass: 'my-class-name', errorClass: 'still-my-class-name' });

Change class handler

Add parsley-success and parsley-error to direct parent:

    $('#form').parsley( {
        errors: {
            classHandler: function ( elem, isRadioOrCheckbox ) {
                return $( elem ).parent();
            }
        }
    } );

Change error container

Override the container that the `errorWrapper` (ie. by default the `<ul></ul>` containing the errors) is inserted into.

By default this function does not return anything and so the `errorWrapper` is added to the DOM directly after the element containing the error, however if you override this function in your options you can return an alternative container where the `errorWrapper` will be appended

For example, to have the error messages appear before the field with the error in a `div` with the class `.parsley-container`:

    errors: {
        container: function (element, isRadioOrCheckbox) {
            var $container = element.parent().find(".parsley-container");
            if ($container.length === 0) {
                $container = $("<div class='parsley-container'></div>").insertBefore(element);
            }
            return $container;
        }
    }

Advanced changes | See `errorsWrapper`, `errorElem` errors properties in Parsley default options.

Top

### Parsley Plugins & Localization

Parsley is shipped with localization (i18n) for its failure messages, and with extra, advanced validators, not included in parsley by default. Learn how to use them here.

#### Localizations

Here are Parsleys error messages in various supported languages. To use one of these, just call the desired language file. Eg: for French messages:

    <script type="text/javascript" src="/i18n/messages.fr.js"></script>
    <script type="text/javascript" src="parsley.js"></script>

Please, feel free to fork and contribute by adding your own translations messages in your language!

### Integration with other frameworks

There is a growing community of tools integrating Parsley with other frameworks. If you create such a tool, please submit a pull request.

- Django
- Rails
- Wicket
- WTForms
- Cascade Framework

Top