Parsley.js is a lightweight, unobtrusive JavaScript library for form validation. It leverages HTML5’s built-in validation features but extends them significantly, providing a flexible and powerful way to manage form validation with minimal code. It works by attaching itself to your existing forms, dynamically adding validation rules and feedback mechanisms without requiring major structural changes to your HTML. Parsley.js focuses on ease of use and a clean, developer-friendly API.
Using Parsley.js offers several advantages:
blur
, change
, submit
).There are several ways to include Parsley.js in your project:
<head>
:<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.9.2/parsley.min.js"></script>
npm install parsleyjs
Then, include it in your project using a module bundler like Webpack or Parcel.
Once included, Parsley.js will automatically initialize on forms with the data-parsley-validate
attribute:
<form data-parsley-validate>
<!-- Your form fields here -->
</form>
Alternatively, you can initialize Parsley.js manually:
$('form').parsley();
This will enable Parsley.js validation on all forms in your document. More detailed initialization options and configuration are covered in subsequent sections.
Parsley.js can be added to your forms in two primary ways: automatically or manually.
Automatic Initialization: The simplest approach is to add the data-parsley-validate
attribute to your <form>
element. Parsley.js will automatically detect and initialize validation on any form with this attribute.
<form data-parsley-validate>
<input type="text" name="name" required>
<button type="submit">Submit</button>
</form>
Manual Initialization: For more control, you can initialize Parsley.js manually using JavaScript. This is useful if you need to customize initialization options or apply validation to forms dynamically.
// Using jQuery (recommended)
$('form').parsley();
// Using plain JavaScript
const forms = document.querySelectorAll('form');
.forEach(form => Parsley.addForm(form)); forms
Validation rules are defined using data attributes on your input fields. The attribute name follows the pattern data-parsley-*
, where *
represents the constraint name (e.g., required
, min
, max
, etc.). The value of the attribute specifies the constraint’s parameter.
<input type="text" name="name" data-parsley-required data-parsley-length="[3, 20]">
<input type="email" name="email" data-parsley-type="email">
In this example:
data-parsley-required
makes the field required.data-parsley-length="[3, 20]"
specifies that the field must have a length between 3 and 20 characters.data-parsley-type="email"
ensures the field contains a valid email address.You can combine multiple constraints on a single field.
Parsley.js provides a range of built-in validation constraints:
required
: The field must have a value.type
: Validates the input type (e.g., “email”, “number”, “url”).length
: Specifies the minimum and maximum length of the input (e.g., [3, 20]
).min
: Specifies the minimum value for numeric or date inputs.max
: Specifies the maximum value for numeric or date inputs.range
: Specifies the allowed range for numeric inputs (e.g., [10, 100]
).pattern
: Validates the input against a regular expression.equalto
: Checks if the field value matches another field’s value.minwords
: Minimum number of words.maxwords
: Maximum number of words.minlength
: Minimum number of characters.maxlength
: Maximum number of characters.For validation needs not covered by built-in constraints, you can create custom constraints. This involves defining a JavaScript function that performs the validation logic and registering it with Parsley.js.
.addValidator('customValidator', {
ParsleyvalidateString: function(value) {
return value.length > 10;
,
}messages: {
en: 'Value must be longer than 10 characters'
}; })
Then, use the custom constraint in your form:
<input type="text" name="customField" data-parsley-custom-validator>
Parsley.js supports various input types, automatically applying appropriate validation rules based on the type. For example, type="email"
triggers email validation, type="number"
enables numeric validation, and so on. You can still override or add constraints using data attributes as needed.
By default, Parsley.js performs validation on input blur
(when the input loses focus) and on form submission. However, you can adjust the validation trigger using the data-parsley-trigger
attribute.
<input type="text" name="name" data-parsley-required data-parsley-trigger="keyup">
This example triggers validation on every keyup event, providing immediate feedback to the user. Other possible trigger values include focus
, change
, and a combination of triggers (e.g., focus blur
).
Conditional validation allows you to apply validation rules based on the values of other fields or the state of the form. This is achieved using the data-parsley-required-if
, data-parsley-required-if-checked
, and similar attributes, which can reference other fields using their selectors.
<input type="checkbox" id="newsletter" name="newsletter"> Subscribe to Newsletter
<input type="text" id="email" name="email" data-parsley-required-if="#newsletter:checked">
In this example, the email
field becomes required only if the newsletter
checkbox is checked. Other conditional attributes include data-parsley-required-if-value
, data-parsley-min
, data-parsley-max
, and more, allowing sophisticated conditional logic.
Parsley.js supports remote validation, where the validity of an input is checked against a server-side script. This is particularly useful for checking for unique usernames, verifying email addresses, or performing other server-dependent checks. Use the data-parsley-remote
attribute to specify the URL of the remote validation script.
<input type="text" name="username" data-parsley-remote="/api/check-username">
The remote script should return a JSON response with a valid
property (true or false).
Asynchronous validation handles validation tasks that require time, such as making API calls. Parsley.js seamlessly integrates with asynchronous validation through the data-parsley-remote
attribute and promises. The ParsleyField.asyncValidate
method gives more control over asynchronous validation processes.
// Example using a promise
const usernameField = $('#username');
.on('parsley:field:validate', function() {
usernameFieldconst promise = new Promise((resolve, reject) => {
setTimeout(() => {
const isValid = checkUsernameAvailability(usernameField.val()); // Your check function
resolve(isValid);
, 1000); // Simulate delay
};
}).parsley().asyncValidate(promise);
usernameField;
})
You can add or remove validation rules dynamically using JavaScript. This is useful in scenarios where validation requirements change based on user interaction or other events.
// Add a required rule
$('#myField').parsley().addConstraint('required', true);
// Remove a rule
$('#myField').parsley().removeConstraint('required');
// Update an existing constraint
$('#myField').parsley().updateConstraint('length', '[5, 10]');
Parsley.js provides several ways to handle validation errors:
data-parsley-*
attributes.parsley:field:error
, parsley:form:error
) to trigger custom error handling logic.Parsley.js supports internationalization through the use of message files. You can create separate message files for different languages and load them dynamically based on the user’s locale. Parsley.js uses i18n
for this purpose. You will typically define a messages
object within your custom validators or utilize existing translations available from Parsley.js or community contributions. This involves defining a mapping of constraint names to translated messages for each language. Parsley.js then uses the user’s locale (usually automatically determined, or explicitly set) to select the appropriate message file.
By default, Parsley.js prevents the default form submission behavior if the form is invalid. This prevents the form from being submitted to the server until all validation rules are met. This behavior is typically desired, ensuring data integrity. However, you might need to control this behavior in certain circumstances.
To override this default behavior and allow submission even with validation errors, set the data-parsley-trigger
attribute to submit
only, preventing other triggers from interfering. If the form is invalid, the parsley:form:submit
event will still fire, allowing you to handle invalid form submission in your custom logic.
<form data-parsley-validate data-parsley-trigger="submit">
<!-- Your form fields here -->
</form>
Alternatively, you can handle the form submission event using JavaScript and manually prevent the default action.
Parsley.js provides several events related to form submission that you can use to customize the submission process. The most relevant events are:
parsley:form:init
: Fired when the Parsley form instance is initialized.parsley:form:validated
: Fired after all fields in the form have been validated. The form’s validity status is available via the isValid()
method.parsley:form:submit
: Fired when the form is submitted (whether valid or invalid). The event object includes the form instance and the validity status. This is the event you should typically handle to perform actions after validation is complete.parsley:form:error
: Fired when the form validation fails.parsley:form:success
: Fired when the form validation succeeds.$('form').on('parsley:form:submit', function (event) {
if (event.parsley.isValid()) {
// Perform submission actions (e.g., AJAX call)
alert('Form submitted successfully!');
else {
} // Handle validation errors
alert('Form contains errors. Please correct them.');
// Optionally prevent default submission
event.preventDefault();
}; })
You can fully customize form submission behavior using the events described above. For instance, you can:
Parsley.js works well with AJAX. Instead of relying on the default form submission, you can handle the parsley:form:submit
event and perform an AJAX request to submit the form data asynchronously:
$('form').on('parsley:form:submit', function (event) {
if (event.parsley.isValid()) {
.ajax({
$type: 'POST',
url: '/submit-form',
data: $(this).serialize(),
success: function(response) {
// Handle successful submission
alert('Form submitted successfully!');
,
}error: function(error) {
// Handle submission errors
alert('Error submitting form: ' + error.responseText);
};
})event.preventDefault(); // Prevent default form submission
}; })
Parsley.js is designed to work well with other JavaScript libraries. It doesn’t impose any specific framework requirements and integrates easily with:
This section provides a comprehensive overview of the Parsley.js API, including methods, options, events, and utility functions. For detailed information and examples, refer to the full API documentation on the Parsley.js website.
Parsley.js provides several methods for interacting with Parsley instances (forms and fields). Key methods include:
validate()
: Triggers validation for a Parsley instance.isValid()
: Returns true
if the instance is valid, false
otherwise.reset()
: Resets the validation state of a Parsley instance, clearing errors and resetting the validity status.destroy()
: Removes Parsley from a form or field.addError(errorMessage)
: Adds a custom error message to a field.removeError(errorMessage)
: Removes a specific error message.getErrors()
: Returns an array of error messages.updateConstraint(name, value)
: Updates the value of an existing constraint.addConstraint(name, value, priority)
: Adds a new constraint to a field.removeConstraint(name)
: Removes a constraint from a field.asyncValidate(promise)
: Performs asynchronous validation using a promise.These methods can be called on both ParsleyForm
instances (for forms) and ParsleyField
instances (for individual fields). For example:
// On a form:
$('form').parsley().validate();
// On a field:
$('#myField').parsley().addError('Custom error message');
Parsley.js offers various options for configuring its behavior. These options can be set globally or on individual forms. Key options include:
trigger
: Specifies the events that trigger validation (e.g., “focusin”, “change”, “keyup”).focus
: Controls whether to focus on the first invalid field after validation.priorityEnabled
: Enables/disables constraint priority.excluded
: A CSS selector specifying elements to exclude from validation.errorClass
: The CSS class applied to invalid fields.successClass
: The CSS class applied to valid fields.classHandler
: A custom function for handling the addition and removal of CSS classes.errorsWrapper
: A CSS selector specifying the element to wrap error messages in.errorsContainer
: A CSS selector specifying where to place error messages.errorMessage
: A function that generates error messages.messages
: An object containing custom error messages for different languages.Options can be set globally using Parsley.options
or locally on a form using data attributes (e.g., data-parsley-trigger="change"
).
Parsley.js triggers numerous events throughout its lifecycle. These events allow you to hook into various stages of the validation process and customize behavior. Some important events include:
parsley:field:init
: Fired when a field is initialized.parsley:field:validate
: Fired before a field’s validation.parsley:field:validated
: Fired after a field’s validation.parsley:field:success
: Fired when a field is valid.parsley:field:error
: Fired when a field is invalid.parsley:form:init
: Fired when a form is initialized.parsley:form:validated
: Fired after form validation.parsley:form:submit
: Fired before a form is submitted (whether valid or invalid).parsley:form:success
: Fired when a form is valid and about to be submitted.parsley:form:error
: Fired when a form is invalid.These events can be listened to using jQuery’s on
method or the standard addEventListener
method:
$('form').on('parsley:form:validated', function() {
// Handle form validation
; })
The Parsley constraint API allows you to define and manage validation constraints. You can access existing constraints, add custom constraints, and control constraint priority. Key methods include addValidator
, removeValidator
, getValidators
, addConstraint
, removeConstraint
, and updateConstraint
. This API provides fine-grained control over the validation rules applied to fields.
Parsley.js provides a few utility functions for common tasks:
Parsley.Utils.trim
: Trims whitespace from a string.Parsley.Utils.attr
: Gets the value of an attribute, handling potential null values gracefully.Parsley.Utils.setAttr
: Sets the value of an attribute.Parsley.Utils.parseRequirement
: Parses validation requirements from data attributes.These functions can be helpful for custom validation logic or other tasks related to Parsley.js. Consult the official documentation for detailed usage examples.
Parsley.js is designed to be lightweight and efficient, but certain practices can further enhance its performance:
data-parsley-trigger
values to optimize validation timing. Real-time validation on every keystroke (keyup
) can be resource-intensive; consider using blur
or change
for less frequent updates.If you encounter issues, several techniques can aid in debugging Parsley.js:
console.log()
statements in your code to inspect the values of variables and track the execution flow. This can be helpful in understanding why certain validations are failing.isValid()
, getErrors()
, and the constraints defined on the instance to investigate the validation state.data-parsley-validate
attribute (or are manually initialized), and validation rules are correctly defined using data attributes. Check your browser’s console for errors.data-parsley-required-if
) and ensure they accurately target the elements influencing the conditional rules.Parsley.js is designed to be extensible, allowing developers to customize its behavior and add new features. This section explains how to create custom constraints, add custom validators, extend core functionality, and contribute to the Parsley.js project itself.
Custom constraints extend Parsley.js by adding new validation rules. They’re defined using the Parsley.addValidator
method, providing a validation function and associated messages.
.addValidator('customConstraint', {
ParsleyvalidateString: function(value, requirement) {
// Your validation logic here. 'requirement' is the value specified in the data attribute.
return value.length >= requirement;
,
}requirementType: 'integer', // Specify the type of requirement (optional)
messages: {
en: 'Value must be at least %s characters long'
}; })
This code defines a constraint named “customConstraint” that checks if a string’s length is greater than or equal to a specified requirement. The requirementType
defines the type of data expected for the requirement (here, an integer). The messages
object contains localized error messages. You can then use this constraint in your form:
<input type="text" name="myField" data-parsley-custom-constraint="10">
Custom validators extend Parsley.js by adding new validation functions. They’re also defined using Parsley.addValidator
, but instead of focusing on a specific constraint, you define a more general validation function.
.addValidator('isEven', {
ParsleyvalidateString: function(value) {
return parseInt(value) % 2 === 0;
,
}messages: {
en: 'Value must be an even number'
}; })
This creates a validator named isEven
that checks if a value is an even number. You use it with data-parsley-isEven
attribute.
Extending Parsley.js beyond custom constraints and validators involves modifying its core behavior or adding new features. This usually involves creating a plugin. A Parsley plugin is a function that receives the Parsley instance as an argument and allows modification of its options, events, or internal behavior.
.on('parsley:field:init', function (fieldInstance) {
Parsley// Access the Parsley field instance and modify its behavior
.options.classHandler = function(element, isError) {
fieldInstance// Your custom class handler
;
}; })
This example modifies the default class handler for Parsley fields. For more complex extensions, you might need to create a separate JavaScript file, encapsulate your extension within a function, and then include it in your project.
To contribute to Parsley.js, you should:
Before contributing, carefully review the project’s contribution guidelines and coding style to ensure your contributions align with the project’s standards. Your contributions must meet the project’s quality standards and be thoroughly tested before being merged.