### 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 `
` element, it returns a `ParsleyForm` instance. ### Options | Property | Default | | ------------------------- | ----------------------------------------------------------------------- | | `data-parsley-namespace` | `data-parsley-` | | `data-parsley-validate` | Auto bind your form with Parsley validation on document load. | | `data-parsley-priority-enabled` | `true` | | `data-parsley-inputs` | `input, textarea, select` | | `data-parsley-excluded` | `input[type=button], input[type=submit], input[type=reset], input[type=hidden]` | ### Option Descriptions - **`data-parsley-namespace`**: Namespace used by Parsley DOM API to bind options from DOM. [See more](#data-attrs) - **`data-parsley-validate`**: Automatically binds the form with Parsley validation on document load. - **`data-parsley-priority-enabled`**: If `true`, validates higher priority constraints first and stops on the first failure. If `false`, validates all constraints simultaneously and shows all failing ones. - **`data-parsley-inputs`**: Selector for fields within a form to be validated by Parsley. These fields are further filtered by the `excluded` option. - **`data-parsley-excluded`**: Selector for form fields that should NOT be validated by Parsley. Example to exclude disabled and hidden fields: `input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden` ``` -------------------------------- ### Extend Factory with Base Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/main.html Inherits actualizeOptions and _resetOptions methods to the Factory prototype, enabling access to base functionalities during factory operations. ```javascript Object.assign(Factory.prototype, Base.prototype); ``` -------------------------------- ### Build Parsley UI Elements Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/ui.html Initializes and builds the necessary UI elements for Parsley validation feedback. This method should be called before interacting with UI components and ensures UI is only built once. ```javascript if (this._ui || false === this.options.uiEnabled) return; var _ui = {}; ``` -------------------------------- ### Fix Suite.clone() .ctx Reference Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md Corrects a reference issue in `Suite#clone()` related to the `.ctx` property, ensuring proper context cloning. ```javascript Fixed `Suite#clone()` `.ctx` reference. Closes #262 ``` -------------------------------- ### jQuery Promise.all Polyfill Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/utils.html Provides an alternative to the native Promise.all for handling multiple jQuery promises. It ensures consistent behavior by adding extra arguments. ```javascript return $.when(...promises, 42, 42); ``` -------------------------------- ### Add 'specify' Synonym for 'it' Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md Introduces 'specify' as a synonym for 'it' in the BDD interface, offering alternative syntax. ```javascript Added "specify" synonym for "it" [domenic] ``` -------------------------------- ### Track Page View with Google Analytics Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/field.html Asynchronous script to load and execute Google Analytics tracking code. It ensures the `_gaq` object is initialized and then pushes the account ID and page view event. ```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)})(); ``` -------------------------------- ### Add JavaScript API Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md Introduces a comprehensive JavaScript API for programmatic control of Mocha. ```javascript Added js API. Closes #265 ``` -------------------------------- ### Extend Field and Form with Base and UI Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/main.html Supplements Field and Form constructors with methods from Base and UI, ensuring access to core functionalities. ```javascript Object.assign(Field.prototype, UI.Field, Base.prototype); Object.assign(Form.prototype, UI.Form, Base.prototype); ``` -------------------------------- ### Allow Callback for mocha.run() in Client Version Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md Enables the use of a callback function with `mocha.run()` in the client-side version of Mocha. ```javascript Fixed: allow callback for `mocha.run()` in client version ``` -------------------------------- ### Include Parsley.js in HTML Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/expect.js/README.md Method to include the expect.js library in an HTML file via a script tag. ```html ``` -------------------------------- ### Item Template for Universal Widget Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/uwidget/README.md HTML template used to render each item in the collection. It uses ERB-like syntax for dynamic data insertion, displaying comments and issue titles with links. ```html ``` -------------------------------- ### Add --recursive Option Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md Introduces the --recursive option, enabling recursive traversal of test directories. ```bash Added `--recursive` [tricknotes] ``` -------------------------------- ### Download Event Tracking Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/about.html This JavaScript code snippet attaches a click event listener to elements with the class 'download'. It tracks download events and specific versions using Google Analytics. ```javascript $(document).ready(function () { $('.download').on('click', function (event) { _gaq.push(['_trackEvent', 'download', 'download ' + $(this).data('version'), $(this).data('version')]); _gaq.push(['_trackPageview', '/download/' + $(this).data('version')]); }); }); ``` -------------------------------- ### Initialize Multiple Field Group Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/multiple.html Initializes the multiple field group by setting the initial element and creating an array to hold all related elements. ```javascript import $ from 'jquery'; import Utils from './utils'; var Multiple = function () { this.__class__ = 'FieldMultiple'; }; Multiple.prototype = { _init: function () { this.$elements = [this.$element]; return this; } }; export default Multiple; ``` -------------------------------- ### Actualize Options Method Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/base.html Applies options from `domOptions` to the element using `Utils.attr` and recursively calls `actualizeOptions` on the parent if it exists. ```javascript actualizeOptions: function () { Utils.attr(this.element, this.options.namespace, this.domOptions); if (this.parent && this.parent.actualizeOptions) this.parent.actualizeOptions(); return this; } ``` -------------------------------- ### Reset Options Method Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/base.html Resets options by creating a shallow copy of `initOptions` into `this.options` and then calls `actualizeOptions`. ```javascript "\u005F\u005FresetOptions": function (initOptions) { this.domOptions = Utils.objectCreate(this.parent.options); this.options = Utils.objectCreate(this.domOptions); for (var i in initOptions) { if (initOptions.hasOwnProperty(i)) this.options[i] = initOptions[i]; } this.actualizeOptions(); }, ``` -------------------------------- ### Add Markdown Reporter Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md Introduces a 'markdown' reporter that formats test results in GitHub Flavored Markdown. ```javascript Added `markdown` reporter (github flavour) ``` -------------------------------- ### Adding and Managing Validators Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/validator_registry.html Details on how to add, check for, update, and remove validators from the registry. ```APIDOC ## Validator Management API ### Description Provides functionalities to add, retrieve, update, and remove custom validators. ### Methods #### `addValidator(name, validator, priority)` Adds a new validator to the registry. If a validator with the same name already exists, a warning is issued. - **name** (string) - The name of the validator. - **validator** (object | function) - The validator function or an object containing validator properties (e.g., `fn`, `priority`, `messages`). - **priority** (number) - The priority of the validator (used in older API versions). #### `hasValidator(name)` Checks if a validator with the given name exists in the registry. - **name** (string) - The name of the validator to check. - Returns: (boolean) - True if the validator exists, false otherwise. #### `updateValidator(name, validator, priority)` Updates an existing validator. If the validator does not exist, it is added. - **name** (string) - The name of the validator to update. - **validator** (object | function) - The new validator function or properties. - **priority** (number) - The priority of the validator. #### `removeValidator(name)` Removes a validator from the registry. - **name** (string) - The name of the validator to remove. ### Example Usage ```javascript // Add a custom validator window.Parsley.addValidator('mycustom', { validateString: function(value, requirement) { return value === requirement; }, messages: { en: 'This value should be %s', } }); // Check if a validator exists if (window.Parsley.hasValidator('required')) { console.log('Required validator is available.'); } // Remove a validator window.Parsley.removeValidator('mycustom'); ``` ``` -------------------------------- ### Create RegExp with Flags Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/utils.html Constructs a new RegExp object from a pattern string and extracted flags. Handles potential errors if the requirement type is unknown. ```javascript return new RegExp(regexp, flags); ``` -------------------------------- ### Initialize Parsley Form Source: https://github.com/guillaumepotier/parsley.js/blob/master/doc/annotated-source/form.html Constructor for the Form class. Initializes form element, options, and fields. Requires jQuery. ```javascript var Form = function (element, domOptions, options) { this.__class__ = 'Form'; this.element = element; this.$element = $(element); this.domOptions = domOptions; this.options = options; this.parent = window.Parsley; this.fields = []; this.validationResult = null; }; ``` -------------------------------- ### Fix Deprecation Warning for path.existsSync Source: https://github.com/guillaumepotier/parsley.js/blob/master/bower_components/mocha/HISTORY.md Removes the deprecation warning associated with using `path.existsSync` by updating to a recommended alternative. ```javascript Fixed deprecation warning when using `path.existsSync` ```