Parsley Documentation

### Parsley

Tweet

# Overview

### Frontend form validation

Parsley is a javascript form validation. It helps you providing your users feedbacks on their form submission before sending it to your server. It saves you bandwith, server load and it saves time for your user.

This javascript form validation is not necessary, and if used, this do not replace a strong backend server validation.

That's why Parsley is here: to let you define your general form validation, implement it on the backend side, and simply port it frontend-side, with maximum respect to user experience best practices.

#### Parsley 1.x versions

Parsley curent stable and supported versions are 2.x. If you still use a 1.x version, here is the related doc. But don't forget to upgrade!

### Data attributes

Parsley use a specific DOM API that allow to configure pretty much everything directly from your DOM, without writting a single javascript configuration line ou custom function. Parsley default DOM API is `data-parsley-`. That means that if in config you see a `foo` property, it could be setted/modified via DOM with `data-parsley-foo="value"`.

#### More on Parsley DOM API

1. For composed property names, Parsley uses camelization, like jQuery `$.data()` does. That means that `data-parsley-composed-property` will correspond in code to `composedProperty`, and reciprocally.
2. Every property set in DOM will be stored in `this.options` for each Parsley instance.
3. You can change the DOM API namespace directly in DOM (inception), by doing `data-parsley-namespace="data-my-namespace-"` and then your Parsley DOM attributes will look like `data-my-namespace-property="value"`.

### Configuration

You'll see along this documentation and through examples various available configuration options. You can also have a pretty overview here of Parsley's default configuration options.

# Installation

### Basic installation

Parsley rely on jQuery (>= 1.6) that would need to be called before including Parsley.

Then, you can either use `parsley.js` unminified file or `parsley.min.js` minified one. These files and other builds (Remote, Extras..) are available here.

Finally, add `data-parsley-validate` to each `<form>` you want to be validated.

That would look pretty much like this:

    <script src="jquery.js"></script>
    <script src="parsley.min.js"></script>

    <form data-parsley-validate>
    ...
    </form>

#### Parsley CSS

Parsley adds many classes and elements in the DOM when it validates. You are strongly encouraged to customize them in your own stylesheets, but here is the "standard" Parsley css file that is used here on the documentation and examples, if you want to use it to bootstrap your projects with Parsley.

### Javascript installation

Like for Basic installation, manage to require jQuery and Parsley. Then, simply use `$('#form').parsley(options);` or `new Parsley('#form', options);` (where `options` is an optional configuration object) to manually bind Parsley to your forms.

That would look pretty much like this:

    <script src="jquery.js"></script>
    <script src="parsley.min.js"></script>

    <form id="form">
    ...
    </form>

    <script type="text/javascript">
      $('#form').parsley();
    </script>

#### Do not add `data-parsley-validate` to your forms

Please be aware that parsley looks on document load at all `data-parsley-validate` occurences in DOM and automatically bind them if valid.
Once a form or field instance is binded by Parsley, default instanciation options could not be easily updated, only the ones defined in the DOM. That means that if this DOM validation attribute is present, doing `$('#form').parsley(options);` would just return the automatically already binded instance, and not the one you would expect with the `options` you wanted to set.

### Localization

Parsley comes with various error messages for its built-in validators. They are shipped in English by default, but many other languages are available, thanks to the awesome international Parsley community. See the available localizations here.

To load a different locale and its messages, you have two possibilities:

- Load your needed localization before parsley, then select the one you need then once Parsley is loaded and if you want to switch from the English default one. In this example, we'll load both French and Italian translations, and use French:

      <script src="jquery.js"></script>
      <script src="i18n/fr.js"></script>
      <script src="i18n/it.js"></script>
      <script src="parsley.min.js"></script>
      <script type="text/javascript">
        window.ParsleyValidator.setLocale('fr');
      </script>

- Load your needed localization after parsley. Last loaded file will automatically set the messages locale for ParsleyValidator. In this example, we'll load both French and Italian translations, and use Italian:

      <script src="jquery.js"></script>
      <script src="parsley.min.js"></script>
      <script src="i18n/fr.js"></script>
      <script src="i18n/it.js"></script>

### Plugins

Parsley strive to be well decoupled and modular. It uses events and inheritance, that allows various plugins.

Current available plugins are:

- Parsley Remote: provide an ajax validator and an asynchronous validation
- Parsley Extras: provide some extras useful validators

# Usage

### Overview

Parsley is a decoupled library that uses differents classes to do the heavy work. You'll see here the different protagonists involved and how you can configure them to fit your desired validation.

#### Look at the source code!

Of course, this documentation strive to be the most exhaustive possible and relatively easy to understand. This documentation also provide the complete annotated source. Please take 5 minutes of your time to have a quick glance at it, and at least understand the architecture (Parsley, ParsleyForm, ParsleyField, ParsleyValidator, ParsleyUI, Utils, Pub/Sub..), it will heavily ease the lecture below.

### Form

When doing `$('#target').parsley()` or `new Parsley('#target');` on a `<form id="target">` element, it will bind the whole form and its various inputs and return you a `ParsleyForm` instance.

#### Field options inheritance

All the options you pass through DOM or constructor for a form will be inherited by every `ParsleyField` input instance that belongs to the form. This is a handy way to configure all your form's inputs in a row by passing their config through form.

#### Options

Property | Default | Description
--- | --- | ---
`data-parsley-namespace` #2.0 | `data-parsley-` | Namespace used by Parsley DOM API to bind options from DOM. See more
`data-parsley-validate` #2.0 | `` | Auto bind your form with Parsley validation on document load.
`data-parsley-priority-enabled` #2.0 | `true` | Either validate higher priority constraints first and stop on first failure (`true`), or validate all constraints simultaneously and show all failing ones (`false`).

#### Methods

Method | Returns | Description
--- | --- | ---
`isValid()` #2.0 | `boolean` | Returns if the Form is valid or not. Does not affect UI nor fires events.
`validate(group)` #2.0 | `boolean` | Validate form. Prevent submission if not valid. Fires events and affect UI.. You can only validate a certain group of fields by specifing optional `group` string parameter.

#### UI

See UI for Form section.

### Field

When doing `$('#target').parsley()` or `new Parsley('#target');` on a `<input id="target">` element (or `<textarea>`, `<select>`), it will bind the field and return you a `ParsleyField` instance.

#### Options

Property | Default | Description
--- | --- | ---
`data-parsley-group` #2.0 | `null` | Assign a group to a field for specifig group validation
`data-parsley-multiple` #2.0 | `null` | You can define a fields' group by giving the same name to radio / checkboxes elements or add a `data-parsley-multiple="mymultiplegroup"` property to each one of them.

#### Methods

Method | Returns | Description
--- | --- | ---
`isValid()` #2.0 | `boolean` | Returns if the Field is valid or not. Does not affect UI nor fires events.
`validate()` #2.0 | `true` if all ok `[]` if empty optional field `[Violation [, Violation..]]` if fails | Validate Field. Fires events and affect UI.

#### UI

See UI for Field section.

# Built-in validators

### Overview

Parsley 2.x is now based on validator.js that ships usual validators and ease a lot group and priority validation. That way, Parsley mutualize validators with validators.js and define new ones using the `Callback()` Assert.

#### Use Validator.js in your Parsley projects

Parsley let you use validator.js in `window.ParsleyValidator.Validator`

### Validators list

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

Required #2.0

`required` | HTML5
`data-parsley-required` |
`data-parsley-required="true"` |
`data-parsley-required="false"` |

Validate that a required field has been filled with a non blank value. If `data-parsley-required="false"`, validator is deactivated and field not required.

Email #2.0

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

Validates that a value is a valid email address.

Number #2.0 | `data-parsley-type="number"` | Validates that a value is a valid number.Warning! HTML5 `type="number"` is binded with below `integer` validator.

Integer #2.0

`type="number"` | HTML5
`data-parsley-type="integer"` |

Validates that a value is a valid integer.

Digits #2.0 | `data-parsley-type="digits"` | Validates that a value is only digits.
Alphanum #2.0 | `data-parsley-type="alphanum"` | Validates that a value is a valid alphanumeric string.

Url #2.0

`type="url"` | HTML5
`data-parsley-type="url"` |

Validates that a value is a valid url.

Minlength #2.0 | `data-parsley-minlength="6"` | Validates that the length of a string is at least as long as the given limit.
Maxlength #2.0 | `data-parsley-maxlength="10"` | Validates that the length of a string is not larger than the given limit.
Length #2.0 | `data-parsley-length="[6, 10]"` | Validates that a given string length is between some minimum and maximum value.

Min #2.0

`min="6"` | HTML5
`data-parsley-min="6"` |

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

Max #2.0

`max="10"` | HTML5
`data-parsley-max="6"` |

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

Range #2.0

`type="range"` | HTML5
`data-parsley-type="range"` |

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

Pattern #2.0

`pattern="\d+"` | HTML5
`data-parsley-pattern="\d+"` |

Validates that a value matches a specific regular expression.

MinCheck #2.0 | `data-parsley-mincheck="3"` | Validates that a certain minimum number of checkboxes in a group are checked.
MaxCheck #2.0 | `data-parsley-maxcheck="3"` | Validates that a certain maximum number of checkboxes in a group are checked.
Check #2.0 | `data-parsley-check="[1, 3]"` | Validates that the number of checked checkboxes in a group is with a certain range.
Check #2.0 | `data-parsley-equalto="#anotherfield"` | Validates that value is identical to another field value (useful or password confirmation check).

These validators are shipped in `parsley.js`. Have a look at Parsley Remote plugin and Parsley Extras for more validators.

### Craft yours!

Of course, Parsley built-in validators are well used and usual validators, and you'll need some more that fit your specific forms and validations. That's why Parsley let you easily create your own validators.

Here again, like localizations, configuring your custom validators and error messages comes with two flavors:

- By registering them in some globals before calling `parsley.js`:

      <input type="text" data-parsley-multiple="3" />
      [...]
      <script type="text/javascript">
      window.ParsleyConfig = {
        validators: {
          multiple: {
            fn: function (value, requirement) {
              return 0 === value % requirement;
            },
            priority: 32
          }
        },
        i18n: {
          en: {
            multiple: 'This value should be a multiple of %s'
          },
          fr: {
            multiple: 'Cette valeur doit être un multiple de %s'
          }
        }
      };
      </script>

- By registering them in `ParsleyValidator` after that `parsley.js` is loaded:

      <input type="text" data-parsley-multiple="3" />
      [...]
      <script type="text/javascript">
      window.ParsleyValidator
        .addValidator('multiple', function (value, requirement) {
          return 0 === value % requirement;
        }, 32)
        .addMessage('en', 'multiple', 'This value should be a multiple of %s')
        .addMessage('fr', 'multiple', 'Cette valeur doit être un multiple de %s');
      </script>

# UI/UX

### Overview

Parsley ships a UI/UX component that is the only one responsible for classes, error messages, focus or trigger events that alterate your page. It strives to be the most UX friendly. Here are the main motto for ParsleyUI:

1. 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!.
2. One error at the time: constraints are prioritized in Parsley, and if many of them are not met for a field on validation, only show the most important one.
3. 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.
4. Control focusing on error: on form submission, the first error field is focused to allow the user to easily start fixing errors.

Naturaly, all this is absolutely customizable, you'll see below how to configure your desired UX behavior.

### Classes and templates

Parsley adds its share of classes and elements. to be continued..

### UI for form

Name | API | Description
--- | --- | ---
UI Enabled #2.0 | `data-parsley-ui-enabled="false"` | Activate or deactivate UI
Focus #2.0 | `data-parsley-forcus="first"` | Focus failing field on form validation. Possible values: `'first' | 'last' | 'none'```

### UI for field

Name | API | Description
--- | --- | ---
Trigger #2.0 | `data-parsley-trigger="change"` | Specify one or many javascript events that will trigger item validation. To set multiple events, separate them by a space `data-parsley-trigger="focusin focusout"`. See the various events supported by jQuery.
No focus #2.0 | `data-parsley-no-focus` | If this field fails, do not focus on it (if `first` focus strategy is on, next field would be focused, if `last` strategy is on, previous field would be focused)
Validation threshold #2.0 | `data-parsley-validation-threshold="10"` | Used with trigger option above, for all `key`- events, do not validate until field have a certain number of characters. Default is `3`
Class handler #2.0 | `data-parsley-class-handler="#element"` | Specify the existing DOM container where ParsleyUI should add error and success classes. It is also possible to configure it with a callback function from javascript, see
Errors container #2.0 | `data-parsley-errors-container="#element"` | Specify the existing DOM container where ParsleyUI should put the errors. It is also possible to configure it with a callback function from javascript, see
Error message #2.0 | `data-parsley-error-message="my message"` | Customize an unique global message for the field.
Validator error message #2.0 | `data-parsley-`constraint`-message="my message"` | Customize the error message for the field constraint. eg: data-parsley-required-message="this field is required"

# Events

### Overview

Parsley comes with a tiny pub/sub mechanism that allows ParsleyUI to work. Further more, it could allow you to do some powerful magic if you listen properly to the right events!

### Events List

Name | Instance | Fired by | Description
--- | --- | --- | ---
`parsley:form:init` #2.0 | `ParsleyForm` | `new Parsley()` | Fired when a Form is binded for the first time.
`parsley:form:validate` #2.0 | `ParsleyForm` | `.validate()` | Fired when a form validation is triggered, before its validation.
`parsley:form:validated` #2.0 | `ParsleyForm` | `.validate()` | Fired when a form validation is triggered, after its validation.
`parsley:field:init` #2.0 | `ParsleyField` | `new Parsley()` | Fired when a Field is binded for the first time.
`parsley:field:validate` #2.0 | `ParsleyField` | `.validate()` | Fired when a field validation is triggered, before its validation.
`parsley:field:success` #2.0 | `ParsleyField` | `.validate()` | Fired when a field validation went well.
`parsley:field:error` #2.0 | `ParsleyField` | `.validate()` | Fired when a field validation failed.

### Usage

Method | Description
--- | ---
`$.listen('name', callback)` #2.0 | Listen a specific event. Fire a callback function.
`$.listen('name', context, callback)` #2.0 | Listen a specific event. Fire a callback function that would have a specific context.
`.subscribe('name', callback)` #2.0 | On a `ParsleyField`, it would only be fired if the specific event is fired by the specific field. On a `ParsleyForm`, it would be fired if the event is fired by the form, or by any of its fields.
`.unsubscribe('name')` #2.0 | Unsubscribe all callbacks subscribed to an event name.
`$.emit('name')` #2.0 | Emit an event for listeners and subscribers.

# Parsely Remote

Parsley remote is a handy plugin that adds an unique ajax asynchronous validator: `data-parsley-remote="http://url.ext"`. It adds these asynchronous methods to Parsley: `.asyncIsValid()` and `.asyncValidate()`.

By default, it will make a `GET` request to the url given in the DOM, and send as parameter the field's value within its name or id. Standard jQuery `$.ajax` options could be passed with `data-parsley-remote-options`.

    <input name="q" type="text" data-parsley-remote-reverse="true" data-parsley-remote="http://myapi.com" data-parsley-remote-options='{ method: "POST", dataType: "jsonp", "data": { "anothervar": "value" } }' value="foo" />

The above code will make a `POST` querry to `http://myapi.com` sending `q='foo'` and `anothervar=value`. By default, a non 2xx ajax response is considered as a failure, but sometimes (when a call is needed to see if an email, a pseudo is available) a 404 API answer could be the right answer, that's why the `reverse` option is here, to throw an error if the request is a success.

To use this plugin, either load `parsley.remote.js` before loading `parsley.js`, either directly load `parsley+remote.js`.

# Parsely Extras

You'll find in the `src/extra/` directory in Parsley .zip or Github projects many more or less useful validators crafted by the community. A doc here is coming.