### Install Dependencies and Run Tests
Source: https://github.com/guillaumepotier/parsley.js/blob/master/CONTRIBUTING.md
Commands to set up the project locally and run tests. Ensure you have Node.js and npm installed. 'npm install' is only needed once.
```bash
npm install
gulp test
gulp test-browser
```
--------------------------------
### Install Grunt CLI and Dependencies
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/bootstrap/README.md
Commands to install the Grunt CLI globally and then install local dependencies for the Bootstrap project.
```bash
npm install -g grunt-cli
```
```bash
npm install
```
--------------------------------
### Install Dev Environment and Run Tests
Source: https://github.com/guillaumepotier/parsley.js/blob/master/README.md
Installs global dependencies and project dependencies for development. Run tests in the terminal.
```bash
npm install -g gulp
npm install
gulp test
```
--------------------------------
### Install Dependencies for Running Tests
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/expect.js/README.md
Commands to clone the repository and install necessary developer dependencies for running tests.
```bash
git clone git://github.com/LearnBoost/expect.js.git expect
cd expect && npm install
```
--------------------------------
### Run Browser Tests
Source: https://github.com/guillaumepotier/parsley.js/blob/master/README.md
Starts a server for running tests in the browser. Access tests by navigating to test/runner.html.
```bash
gulp test-browser
```
--------------------------------
### Install Parsley.js with NPM
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/expect.js/README.md
Command to install the expect.js library using Node Package Manager.
```bash
$ npm install expect.js
```
--------------------------------
### Install Parsley.js with npm
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/download.html
Use this command to install Parsley.js as a dependency in your project using npm.
```bash
$ npm install --save parsleyjs
```
--------------------------------
### Install Parsley.js with Bower
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/download.html
Use this command to install Parsley.js as a dependency in your project using Bower.
```bash
$ bower install --save parsleyjs
```
--------------------------------
### Basic Parsley.js Installation
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/index.html
Include jQuery and Parsley.js before your form. Add `data-parsley-validate` to your form tag to enable automatic validation on document load.
```html
```
--------------------------------
### Parsley Option Inheritance Example
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/index.html
Demonstrates how field instances inherit options from form instances and global options. Changes to higher-level options are automatically reflected in lower-level instances.
```html
```
```javascript
Parsley.options.maxlength = 42;
var formInstance = $('form').parsley();
var field = $('input').parsley();
console.log(field.options.maxlength); // Shows that maxlength is 42
Parsley.options.maxlength = 30;
console.log(field.options.maxlength); // Shows that maxlength is automagically 30
formInstance.options.maxlength++;
console.log(field.options.maxlength); // Shows that maxlength is automagically 31
```
--------------------------------
### JavaScript Installation of Parsley.js
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/index.html
After including jQuery and Parsley.js, you can manually bind Parsley to a form using its ID. This method allows for passing configuration options.
```html
```
--------------------------------
### Testing a Math Function with Parsley.js and Mocha
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/expect.js/README.md
Example of using Parsley.js assertions within a Mocha test suite to test a simple 'add' function.
```javascript
describe('test suite', function () {
it('should expose a function', function () {
expect(add).to.be.a('function');
});
it('should do math', function () {
expect(add(1, 3)).to.equal(4);
});
});
```
--------------------------------
### Parsley.js Localization Setup
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/index.html
Include Parsley.js and then the desired language file(s) after jQuery. The last loaded language file will set the default locale for Parsley's error messages.
```javascript
```
--------------------------------
### Build Distribution Files
Source: https://github.com/guillaumepotier/parsley.js/blob/master/README.md
Builds the distribution files for the project and the annotated source documentation.
```bash
gulp build
```
--------------------------------
### Add mocha init Command
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Provides a new command `mocha init ` to easily copy client-side files for Mocha projects.
```bash
Added `mocha init ` to copy client files
```
--------------------------------
### Run Tests in Node.js
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/expect.js/README.md
Command to execute the test suite using the 'make' utility in a Node.js environment.
```bash
make test
```
--------------------------------
### Anchor RegExp String
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/utils.html
Adds start ('^') and end ('$') anchors to a regular expression string. This ensures the pattern matches the entire string.
```javascript
regexp = '^' + regexp + '$';
```
--------------------------------
### Run Grunt Build
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/bootstrap/README.md
Executes local tests and compiles CSS and JavaScript into the /dist directory using Recess and UglifyJS.
```bash
grunt
```
--------------------------------
### Base Class Prototype Properties
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/base.html
Sets up the prototype for the Base class, including a deprecated `asyncSupport` flag and methods for managing validation pipes.
```javascript
Base.prototype = {
asyncSupport: true, // Deprecated
"_pipeAccordingToValidationResult": function () {
var pipe = () => {
var r = $.Deferred();
if (true !== this.validationResult)
r.reject();
return r.resolve().promise();
};
return [pipe, pipe];
},
```
--------------------------------
### Add Palindrome Validator to Parsley.js
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/examples/customvalidator.html
Use this validator to check if a string is a palindrome (reads the same forwards and backward). It requires no specific setup beyond Parsley.js itself.
```javascript
window.Parsley.addValidator('palindrome', {
validateString: function(value) {
return value.split('').reverse().join('') === value;
},
messages: {
en: 'This string is not the reverse of itself',
fr: "Cette valeur n'est pas l'inverse d'elle même."
}
});
```
--------------------------------
### Compile CSS and JavaScript with Grunt
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/bootstrap/README.md
Creates the /dist directory with compiled files using Recess and UglifyJS.
```bash
grunt dist
```
--------------------------------
### Parsley Initialization
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/index.html
Demonstrates how to initialize Parsley on form and field elements, and the return types for different scenarios.
```APIDOC
## Parsley Initialization
### Overview
Parsley can be initialized on form elements, individual input fields, or multiple elements.
### Method
`$('#selector').parsley(options)`
### Usage Examples
- **On a form element:**
```javascript
$('#existingForm').parsley(options);
```
Returns: `ParsleyForm` instance
- **On an input field:**
```javascript
$('#existingInput').parsley(options);
```
Returns: `ParsleyField` instance
- **On a non-existing DOM element:**
```javascript
$('#notExistingDOMElement').parsley(options);
```
Returns: `undefined`
- **On multiple elements:**
```javascript
$('.multipleElements').parsley(options);
```
Returns: `Array[Instances]`
```
--------------------------------
### Add Quick Syntax Highlighting
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Implements basic syntax highlighting for code snippets within the output.
```javascript
Added quick n dirty syntax highlighting. Closes #248
```
--------------------------------
### Get Constraints Grouped by Priority
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/field.html
Internal method that returns validation constraints grouped by their priority in descending order. If priority is disabled, it returns all constraints in a single group.
```javascript
_getGroupedConstraints: function () {
if (false === this.options.priorityEnabled)
return [this.constraints];
var groupedConstraints = [];
var index = {};
for (var i = 0; i < this.constraints.length; i++) {
var p = this.constraints[i].priority;
if (!index[p])
groupedConstraints.push(index[p] = []);
index[p].push(this.constraints[i]);
}
groupedConstraints.sort(function (a, b) { return b[0].priority - a[0].priority; });
return groupedConstraints;
}
```
--------------------------------
### Get Parsley Field Value
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/field.html
Retrieves the computed value of a Parsley field. This can be overridden by DOM attributes or explicit options. Handles whitespace and ensures a string is returned.
```javascript
getValue: function () {
var value;
if ('function' === typeof this.options.value)
value = this.options.value(this);
else if ('undefined' !== typeof this.options.value)
value = this.options.value;
else
value = this.$element.val();
if ('undefined' === typeof value || null === value)
return '';
return this._handleWhitespace(value);
},
```
--------------------------------
### Add Initial Run of Tests with --watch
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Enables the initial run of tests when the `--watch` option is used, streamlining the development workflow.
```javascript
Added: initial run of tests with `--watch`. Closes #345
```
--------------------------------
### Add Support for Arbitrary Compilers
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Enables support for arbitrary compilers via configuration, allowing for pre-processing of test files.
```javascript
Added support for arbitrary compilers via . Closes #338 [Ian Young]
```
--------------------------------
### Bootstrap Directory Structure
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/bootstrap/README.md
This shows the typical directory structure of a Bootstrap download, including CSS, JS, and font files.
```bash
bootstrap/
├── css/
│ ├── bootstrap.css
│ ├── bootstrap.min.css
│ ├── bootstrap-theme.css
│ └── bootstrap-theme.min.css
├── js/
│ ├── bootstrap.js
│ └── bootstrap.min.js
└── fonts/
├── glyphicons-halflings-regular.eot
├── glyphicons-halflings-regular.svg
├── glyphicons-halflings-regular.ttf
└── glyphicons-halflings-regular.woff
```
--------------------------------
### Get Parsley Error Message
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/ui.html
Retrieves the appropriate error message for a given constraint. It first checks for a custom message defined in options, otherwise it uses the default Parsley message.
```javascript
_getErrorMessage: function (constraint) {
var customConstraintErrorMessage = constraint.name + 'Message';
if ('undefined' !== typeof this.options[customConstraintErrorMessage])
return window.Parsley.formatMessage(this.options[customConstraintErrorMessage], constraint.requirements);
return window.Parsley.getErrorMessage(constraint);
},
```
--------------------------------
### Get Parsley Field Error Messages
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/ui.html
Returns an array of user-friendly error messages for a given field. If the field is valid, an empty array is returned. Otherwise, it formats messages from validation results.
```javascript
if (true === this.validationResult)
return [];
var messages = [];
for (var i = 0; i < this.validationResult.length; i++)
messages.push(this.validationResult[i].errorMessage ||
this._getErrorMessage(this.validationResult[i].assert));
return messages;
```
--------------------------------
### Get Field Value for Validation
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/field.html
Retrieves the field's value, either from a provided argument, configured options, or the DOM element. Handles undefined or null values by returning an empty string after whitespace processing.
```javascript
if ('undefined' === typeof value || null === value)
value = this.getValue();
```
```javascript
if (!this.needsValidation(value) && true !== force)
return $.when();
```
```javascript
var groupedConstraints = this._getGroupedConstraints();
var promises = [];
$.each(groupedConstraints, (_, constraints) => {
```
--------------------------------
### Add npm docs mocha Support
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Enables `npm docs mocha` command to open Mocha's documentation.
```bash
Added `npm docs mocha` support [TooTallNate]
```
--------------------------------
### Run Grunt Tests
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/bootstrap/README.md
Executes JSHint and QUnit tests headlessly in PhantomJS, commonly used for CI environments.
```bash
grunt test
```
--------------------------------
### Get Value from Multiple Fields
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/multiple.html
Retrieves the value from a multiple field group. It handles different input types (radio, checkbox, select multiple) and respects any custom value retrieval logic defined in options.
```javascript
getValue: function () {
// Value could be overriden in DOM
if ('function' === typeof this.options.value)
return this.options.value(this);
else if ('undefined' !== typeof this.options.value)
return this.options.value;
// Radio input case
if (this.element.nodeName === 'INPUT') {
var type = Utils.getType(this.element);
if (type === 'radio')
return this._findRelated().filter(':checked').val() || '';
// checkbox input case
if (type === 'checkbox') {
var values = [];
this._findRelated().filter(':checked').each(function () {
values.push($(this).val());
});
return values;
}
}
// Select multiple case
if (this.element.nodeName === 'SELECT' && null === this.$element.val())
return [];
// Default case that should never happen
return this.$element.val();
},
```
--------------------------------
### Validate Form with Promises
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/form.html
Initiates form validation, handling potential asynchronous operations. It triggers a 'validate' event before refreshing fields and starting the validation process. Allows overriding the default submit event's preventDefault behavior.
```javascript
whenValidate: function ({group, force, event} = {}) {
this.submitEvent = event;
if (event) {
this.submitEvent = Object.assign({}, event, {preventDefault: () => {
Utils.warnOnce("Using \`this.submitEvent.preventDefault()\` is deprecated; instead, call \`this.validationResult = false`");
this.validationResult = false;
}}});
}
this.validationResult = true;
this._trigger('validate');
this._refreshFields();
var promises = this._withoutReactualizingFormOptions(() => {
```
--------------------------------
### Parsley Factory Initialization Logic
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/factory.html
The init method sets up the Parsley instance, pre-computes options, and determines whether to bind the element as a Form or a Field based on its node name and attributes.
```javascript
Factory.prototype = {
init: function (options) {
this.__class__ = 'Parsley';
this.__version__ = 'VERSION';
this.__id__ = Utils.generateID();
this._resetOptions(options);
if (this.element.nodeName === 'FORM' || (Utils.checkAttr(this.element, this.options.namespace, 'validate') && !this.$element.is(this.options.inputs)))
return this.bind('parsleyForm');
return this.isMultiple() ? this.handleMultiple() : this.bind('parsleyField');
},
```
--------------------------------
### Add Custom Async Validator in Parsley.js
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/index.html
Use Parsley.addAsyncValidator to define custom logic for validating AJAX responses. The 'this' keyword inside the function refers to the ParsleyField instance. This example shows how to check the HTTP status code for validation.
```javascript
window.Parsley.addAsyncValidator('mycustom', function (xhr) {
console.log(this.$element);
return 404 === xhr.status;
}, 'http://mycustomapiurl.ext');
```
--------------------------------
### Add Support for Custom Reporters
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Allows users to specify custom reporter modules using the --reporter MODULE command-line option.
```bash
add support for custom reports via `--reporter MODULE`
```
--------------------------------
### Run Tests in Browser
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/expect.js/README.md
Command to run the test suite in a browser environment, typically involving a local server.
```bash
make test-browser
```
--------------------------------
### Prevent Form Submission for Demo
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/examples/ajax.html
Listens for the 'form:submit' event in Parsley and returns false to prevent the default form submission behavior. This is commonly used in examples to allow users to see validation without actually submitting the form.
```javascript
Parsley.on('form:submit', function() {
return false; // Don't submit form for this demo
});
```
--------------------------------
### Initialize the ValidatorRegistry
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/validator_registry.html
The `init` method is used to set up the validator registry with initial validators and a message catalog. It also copies existing validators and adds new ones, triggering a `parsley:validator:init` event.
```javascript
init: function (validators, catalog) {
this.catalog = catalog;
this.validators = Object.assign({}, this.validators);
for (var name in validators)
this.addValidator(name, validators[name].fn, validators[name].priority);
window.Parsley.trigger('parsley:validator:init');
}
```
--------------------------------
### Handle Parsley Form Validation Event
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/examples/events.html
Use the 'form:validate' event to perform custom validation logic. This example checks if at least one of two field groups is valid and updates a custom error message accordingly. Ensure Parsley.js and jQuery are included.
```javascript
$(function () {
$('.demo-form').parsley().on('form:validate', function (formInstance) {
var ok = formInstance.isValid({group: 'block1', force: true}) || formInstance.isValid({group: 'block2', force: true});
$('.invalid-form-error-message')
.html(ok ? '' : 'You must correctly fill *at least one of these two blocks!')
.toggleClass('filled', !ok);
if (!ok) formInstance.validationResult = false;
});
});
```
--------------------------------
### Initialize Universal Widget
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/uwidget/README.md
Initializes the Universal Widget with custom API URL, data handler, template, sorting, direction, and filters. Ensure jQuery is loaded before this script.
```javascript
$(document).ready(function () {
$('.uwidget').UWidget({
url: 'https://api.url.ext',
handler: function (data) {
// special remote data treatment needed ?
return data;
},
template: 'item_tmpl',
sort: {
enabled: true,
name: 'sort',
values: ['created', 'updated', 'comments'],
labels: ['Creation date', 'Update date', 'Comments']
},
direction: {
enabled: true,
name: 'direction',
values: ['desc', 'asc'],
labels: ['Descending', 'Ascending']
},
filters: {
enabled: true,
name: 'labels',
values: ['bug', 'enhancement'],
labels: ['Bug', 'Enhancement']
}
});
});
```
--------------------------------
### Add 'min' Reporter for --watch
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Introduces a 'min' reporter, optimized for use with the `--watch` option, providing concise output.
```javascript
Added "min" reporter, useful for `--watch` [Jakub Nešetřil]
```
--------------------------------
### Initialize Error Wrapper ID and Element
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/ui.html
Sets up the ID for the errors wrapper and selects the element that will contain errors. This is used for displaying validation feedback.
```javascript
_ui.errorsWrapperId = 'parsley-id-' + (this.options.multiple ? 'multiple-' + this.options.multiple : this.__id);
_ui.$errorsWrapper = $(this.options.errorsWrapper).attr('id', _ui.errorsWrapperId);
```
--------------------------------
### Configure Parsley Options
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/main.html
Sets up Parsley's global options by inheriting from Defaults and merging with any existing window.ParsleyConfig. Also updates the old way of accessing global options.
```javascript
Parsley.options = Object.assign(Utils.objectCreate(Defaults), window.ParsleyConfig);
window.ParsleyConfig = Parsley.options; // Old way of accessing global options
```
--------------------------------
### Add .coffee --watch Support
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Enables the `--watch` option for CoffeeScript files, allowing for automatic recompilation and testing.
```coffeescript
Added .coffee `--watch` support. Closes #242
```
--------------------------------
### Add Preliminary Test Coverage Support
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Introduces preliminary support for test coverage analysis, enabling the collection of code coverage data.
```javascript
Added preliminary test coverage support. Closes #5
```
--------------------------------
### Parsley Configuration
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/index.html
Explains how to configure Parsley using data attributes and JavaScript, including option inheritance and namespace customization.
```APIDOC
## Parsley Configuration
### Data Attributes and JavaScript
Options can be set using `data-*` attributes on HTML elements or directly in JavaScript.
#### Example:
```html
```
```javascript
var instance = $('#first').parsley();
console.log(instance.isValid()); // true (maxlength is 42)
$('#first').attr('data-parsley-maxlength', 4);
console.log(instance.isValid()); // false (maxlength is now 4)
// Override options in JavaScript
instance.options.maxlength++; // maxlength is now 5
console.log(instance.isValid()); // true
// Specify options directly during initialization
var otherInstance = $('#second').parsley({
maxlength: 10
});
console.log(otherInstance.options); // { maxlength: 10, ... }
```
### Option Inheritance
Field instances inherit options from their parent Form instances, which in turn inherit from global Parsley options.
#### Example:
```javascript
Parsley.options.maxlength = 42;
var formInstance = $('form').parsley();
var field = $('input').parsley();
console.log(field.options.maxlength); // 42
Parsley.options.maxlength = 30;
console.log(field.options.maxlength); // 30 (automatically updated)
formInstance.options.maxlength++; // 31
console.log(field.options.maxlength); // 31 (automatically updated)
```
### Naming and Namespaces
Customize the DOM API namespace and observe automatic type conversion for data attributes.
#### Example:
```html
```
```javascript
var instance = $('input').parsley({namespace: 'my-namespace-'});
if (false === instance.options.priorityEnabled)
console.log("priorityEnabled was set to false");
```
```
--------------------------------
### Require Parsley.js in Node.js
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/expect.js/README.md
How to import the expect.js library in a Node.js environment using require.
```javascript
var expect = require('expect.js');
```
--------------------------------
### HTML Structure for Universal Widget
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/uwidget/README.md
Basic HTML structure including CSS link, a widget container, and script tags for initialization and the item template. The widget container uses data attributes for configuration.
```html
```
--------------------------------
### Initialize GitHub and Stack Overflow Widgets
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/help.html
Initializes two jQuery widgets: one for displaying GitHub issues and another for Stack Overflow questions related to Parsley.js. Configure the URL, data handler, template, sorting, direction, and filtering options for each widget.
```javascript
$(document).ready(function () {
$('#gh').UWidget({
url: 'https://api.github.com/repos/guillaumepotier/Parsley.js/issues',
handler: function (data) { return data; },
template: 'gh_tmpl',
sort: {
enabled: true,
name: 'sort',
values: ['created', 'updated', 'comments'],
labels: ['Creation date', 'Update date', 'Comments']
},
direction: {
enabled: true,
name: 'direction',
values: ['desc', 'asc'],
labels: ['Descending', 'Ascending']
},
filters: {
enabled: true,
name: 'labels',
values: ['bug', 'request'],
labels: ['Bug', ' Request']
}
});
$('#stack').UWidget({
url: 'https://api.stackexchange.com/2.2/search?tagged=parsley.js&site=stackoverflow',
handler: function (data) { return data.items; },
template: 'stack_tmpl',
sort: {
enabled: true,
name: 'sort',
values: ['creation', 'activity', 'votes', 'relevance'],
labels: ['Creation', 'Activity', 'Votes', 'Relevance']
},
direction: {
enabled: true,
name: 'order',
values: ['desc', 'asc'],
labels: ['Descending', 'Ascending']
}
});
});
```
--------------------------------
### Base Class Initialization
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/base.html
Defines the Base class constructor, which initializes a unique ID for the instance using the Utils module.
```javascript
var Base = function () {
this."__id__ = Utils.generateID();
};
```
--------------------------------
### Parsley.js Download Links
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/download.html
Direct links to download the Parsley.js library files. Includes the full project zip and individual JavaScript files.
```html
[parsley.zip](https://github.com/guillaumepotier/Parsley.js/releases/tag/2.9.2) 250ko
[parsley.js](../dist/parsley.js) 21kb gz
[parsley.min.js](../dist/parsley.min.js) 11kb gz
```
--------------------------------
### Initialize Google Analytics Tracking
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/form.html
This snippet initializes Google Analytics tracking for the page. It ensures that the tracking script is loaded asynchronously and correctly configured.
```javascript
var _gaq=_gaq||[];
_gaq.push(['_setAccount','UA-37229467-1']);
_gaq.push(['_trackPageview']);
(function() {
var e = document.createElement('script'); e.type = 'text/javascript'; e.async = true;
e.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(e, t);
})();
```
--------------------------------
### Import jQuery and Utils in Base.js
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/base.html
Imports necessary libraries, jQuery for DOM manipulation and deferred objects, and a custom Utils module for helper functions.
```javascript
import $ from 'jquery';
import Utils from './utils';
```
--------------------------------
### Expect.js API - Core Assertions
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/expect.js/README.md
This section details the core assertion methods provided by Expect.js, including ok, be, equal, eql, a, an, match, contain, and length.
```APIDOC
## ok
### Description
Asserts that the value is truthy or not.
### Method
`expect(value).to.be.ok()`
`expect(value).to.not.be.ok()`
### Example
```javascript
expect(1).to.be.ok();
expect(true).to.be.ok();
expect({}).to.be.ok();
expect(0).to.not.be.ok();
```
## be / equal
### Description
Asserts strict equality (`===`).
### Method
`expect(value).to.be(expectedValue)`
`expect(value).to.equal(expectedValue)`
`expect(value).to.not.be(expectedValue)`
`expect(value).to.not.equal(expectedValue)`
### Example
```javascript
expect(1).to.be(1);
expect(NaN).not.to.equal(NaN);
expect(1).not.to.be(true);
expect('1').to.not.be(1);
```
## eql
### Description
Asserts loose equality, works with objects.
### Method
`expect(value).to.eql(expectedValue)`
### Example
```javascript
expect({ a: 'b' }).to.eql({ a: 'b' });
expect(1).to.eql('1');
```
## a / an
### Description
Asserts `typeof` with support for `array` type and `instanceof`.
### Method
`expect(value).to.be.a(typeStringOrConstructor)`
`expect(value).to.be.an(typeStringOrConstructor)`
### Example
```javascript
// typeof with optional `array`
expect(5).to.be.a('number');
expect([]).to.be.an('array'); // works
expect([]).to.be.an('object'); // works too, since it uses `typeof`
// constructors
expect(5).to.be.a(Number);
expect([]).to.be.an(Array);
expect(tobi).to.be.a(Ferret);
expect(person).to.be.a(Mammal);
```
## match
### Description
Asserts `String` regular expression match.
### Method
`expect(string).to.match(regex)`
### Example
```javascript
expect(program.version).to.match(/[0-9]+\.[0-9]+\.[0-9]+/);
```
## contain
### Description
Asserts `indexOf` for an array or string.
### Method
`expect(collection).to.contain(value)`
### Example
```javascript
expect([1, 2]).to.contain(1);
expect('hello world').to.contain('world');
```
## length
### Description
Asserts array `.length`.
### Method
`expect(collection).to.have.length(lengthValue)`
### Example
```javascript
expect([]).to.have.length(0);
expect([1,2,3]).to.have.length(3);
```
```
--------------------------------
### Check Each mocha(1) Argument for Directories
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Implements a check for each argument passed to `mocha(1)` to ensure they are valid directories.
```javascript
Added: check each `mocha(1)` arg for directories to walk
```
--------------------------------
### Allow Multiple --globals Usage
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Enables the --globals option to be used multiple times, allowing for a more flexible way to specify global variables.
```bash
Fixed: allow --globals to be used multiple times. Closes #100 [brendannee]
```
--------------------------------
### Add V8 Trace Option Support
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Enables support for V8's --trace-* options, providing deeper insights into JavaScript engine behavior.
```javascript
add v8 `--trace-*` option support
```
--------------------------------
### Base Class Methods
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/base.html
This section covers the core methods of the Base class, including option handling, event management, and validation.
```APIDOC
## Base Class Methods
### Description
Provides fundamental functionalities for Parsley.js instances, including option management, event handling, and validation support.
### Methods
#### `actualizeOptions()`
- **Description**: Updates the element's attributes based on the instance's options and recursively calls `actualizeOptions` on the parent if it exists.
- **Returns**: The current Parsley instance for chaining.
#### `_resetOptions(initOptions)`
- **Description**: Initializes or resets the instance's options. It creates a deep copy of parent options, then shallow copies properties from `initOptions` into the instance's options, and finally calls `actualizeOptions`.
- **Parameters**:
- `initOptions` (object) - An object containing initial options to merge.
#### `on(name, fn)`
- **Description**: Registers a callback function (`fn`) for a given event name (`name`). The callback is executed with the Parsley instance as the context. Returning `false` from a callback will interrupt the execution chain.
- **Parameters**:
- `name` (string) - The name of the event to listen for.
- `fn` (function) - The callback function to execute.
- **Returns**: The current Parsley instance for chaining.
#### `off(name, fn)`
- **Description**: Unregisters a callback function (`fn`) for a given event name (`name`). If `fn` is not provided, all callbacks for the given `name` are removed.
- **Parameters**:
- `name` (string) - The name of the event to unregister from.
- `fn` (function, optional) - The specific callback function to remove.
- **Returns**: The current Parsley instance for chaining.
#### `trigger(name, target, extraArg)`
- **Description**: Triggers an event of the given name (`name`). It executes registered callbacks for the event. If any callback returns `false`, the execution chain is interrupted. It also triggers the event on the parent instance if one exists.
- **Parameters**:
- `name` (string) - The name of the event to trigger.
- `target` (object, optional) - The context for the event callbacks. Defaults to the current instance.
- `extraArg` (any, optional) - An additional argument to pass to the callbacks.
- **Returns**: `true` if the event chain completed without interruption, `false` otherwise.
#### `asyncIsValid(group, force)`
- **Description**: Deprecated. Use `whenValid` instead. Checks if the instance is valid asynchronously.
- **Parameters**:
- `group` (string, optional) - The validation group to check.
- `force` (boolean, optional) - Whether to force validation even if already validated.
- **Returns**: A promise that resolves when validation is complete.
#### `_findRelated()`
- **Description**: Finds related form fields, typically used for multiple fields sharing the same name or validation group.
- **Returns**: A jQuery object containing the related elements.
```
--------------------------------
### Run Terminal Tests
Source: https://github.com/guillaumepotier/parsley.js/blob/master/README.md
Executes the project's tests directly in the terminal.
```bash
gulp test
```
--------------------------------
### Basic Assertions with Parsley.js
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/expect.js/README.md
Demonstrates fundamental assertion patterns using the expect() function for checking undefined values, object equality, and types.
```javascript
expect(window.r).to.be(undefined);
expect({ a: 'b' }).to.eql({ a: 'b' })
expect(5).to.be.a('number');
expect([]).to.be.an('array');
expect(window).not.to.be.an(Image);
```
--------------------------------
### Validator Registry Initialization and Locale Management
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/validator_registry.html
Provides methods for initializing the validator registry with existing validators and managing locale-specific messages.
```APIDOC
## Validator Registry API
### Description
Manages validators and their associated messages for different locales.
### Methods
#### `init(validators, catalog)`
Initializes the validator registry with a set of validators and a message catalog.
- **validators** (object) - An object containing validators to be added.
- **catalog** (object) - An object containing locale-specific messages.
#### `setLocale(locale)`
Sets the current locale for error messages.
- **locale** (string) - The locale code (e.g., 'en', 'fr').
#### `addCatalog(locale, messages, set)`
Adds a new message catalog for a given locale.
- **locale** (string) - The locale code.
- **messages** (object) - An object containing locale-specific messages.
- **set** (boolean) - If true, sets the locale to the newly added catalog.
#### `addMessage(locale, name, message)`
Adds a specific message for a given constraint in a given locale.
- **locale** (string) - The locale code.
- **name** (string) - The name of the constraint.
- **message** (string) - The error message.
#### `addMessages(locale, nameMessageObject)`
Adds multiple messages for a given locale.
- **locale** (string) - The locale code.
- **nameMessageObject** (object) - An object where keys are constraint names and values are messages.
### Example Usage
```javascript
let registry = new ValidatorRegistry(validators, catalog);
registry.setLocale('fr');
registry.addMessage('en', 'myCustomError', 'This is not valid.');
```
```
--------------------------------
### Add Context for BDD Interface
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Introduces the 'context' keyword for the BDD interface, providing an alternative to 'describe'.
```javascript
Added `context` for BDD [hokaccha]
```
--------------------------------
### Create Parsley Form Instance
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/factory.html
Creates and binds a Parsley form instance, extending it with Base and ParsleyExtend.
```javascript
parsleyInstance = $.extend(
new Form(this.element, this.domOptions, this.options),
new Base(),
window.ParsleyExtend
)._bindFields();
```
--------------------------------
### Add Reporter Argument to mocha.run()
Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md
Allows specifying the reporter as an argument to `mocha.run([reporter])`, providing flexibility in reporter selection.
```javascript
Added reporter to `mocha.run([reporter])` as argument
```
--------------------------------
### Google Analytics Tracking
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/factory.html
Initializes Google Analytics tracking by setting the account and tracking a page view.
```javascript
var _gaq=_gaq||[];_gaq.push(["_setAccount","UA-37229467-1"]);_gaq.push(["_trackPageview"])
```
```javascript
var e=document.createElement("script");e.type="text/javascript";e.async=true;e.src=("https:"==document.location.protocol?"https://ssl":"http://www")+".google-analytics.com/ga.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)
```
--------------------------------
### Parsley Form Instance
Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/index.html
Details the options available when initializing Parsley on a form element, which returns a `ParsleyForm` instance.
```APIDOC
## Parsley Form Instance
When `$('#target').parsley()` or `new Parsley('#target')` is called on a `