Parsley.js - Documentation

What is Parsley.js?

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.

Why use Parsley.js?

Using Parsley.js offers several advantages:

Key Features

Setting up Parsley.js

There are several ways to include Parsley.js in your project:

<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.

Basic Validation

Adding Parsley to your forms

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');
forms.forEach(form => Parsley.addForm(form));

Defining Validation Rules

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:

You can combine multiple constraints on a single field.

Built-in Validation Constraints

Parsley.js provides a range of built-in validation constraints:

Custom Validation Constraints

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.

Parsley.addValidator('customValidator', {
  validateString: 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>

Working with different input types

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.

Real-time validation

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).

Advanced Validation Techniques

Conditional Validation

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.

Remote Validation

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

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');
usernameField.on('parsley:field:validate', function() {
  const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      const isValid = checkUsernameAvailability(usernameField.val()); // Your check function
      resolve(isValid);
    }, 1000); // Simulate delay
  });
  usernameField.parsley().asyncValidate(promise);
});

Dynamically Adding/Removing Rules

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]');

Handling Validation Errors

Parsley.js provides several ways to handle validation errors:

Internationalization

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.

Form Submission and Events

Preventing Default Form Submission

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.

Handling Form Submission Events

Parsley.js provides several events related to form submission that you can use to customize the submission process. The most relevant events are:

$('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();
  }
});

Customizing Submission Behavior

You can fully customize form submission behavior using the events described above. For instance, you can:

Working with AJAX

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
  }
});

Integration with other Javascript libraries

Parsley.js is designed to work well with other JavaScript libraries. It doesn’t impose any specific framework requirements and integrates easily with:

API Reference

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 Instance Methods

Parsley.js provides several methods for interacting with Parsley instances (forms and fields). Key methods include:

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 Options

Parsley.js offers various options for configuring its behavior. These options can be set globally or on individual forms. Key options include:

Options can be set globally using Parsley.options or locally on a form using data attributes (e.g., data-parsley-trigger="change").

Parsley Events

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:

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
});

Parsley Constraint API

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.

Utility Functions

Parsley.js provides a few utility functions for common tasks:

These functions can be helpful for custom validation logic or other tasks related to Parsley.js. Consult the official documentation for detailed usage examples.

Best Practices and Troubleshooting

Improving Performance

Parsley.js is designed to be lightweight and efficient, but certain practices can further enhance its performance:

Debugging Parsley.js

If you encounter issues, several techniques can aid in debugging Parsley.js:

Common Issues and Solutions

Tips for Maintainability

Security Considerations

Extending Parsley.js

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.

Creating Custom Constraints

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.

Parsley.addValidator('customConstraint', {
    validateString: 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">

Adding Custom Validators

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.

Parsley.addValidator('isEven', {
  validateString: 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 Functionality

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.

Parsley.on('parsley:field:init', function (fieldInstance) {
    // Access the Parsley field instance and modify its behavior
    fieldInstance.options.classHandler = function(element, isError) {
        // 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.

Contributing to Parsley.js

To contribute to Parsley.js, you should:

  1. Fork the repository: Fork the official Parsley.js repository on GitHub.
  2. Create a branch: Create a new branch for your changes.
  3. Make your changes: Implement your changes, ensuring good code quality, testing, and documentation.
  4. Test your changes: Thoroughly test your changes to ensure they don’t introduce regressions.
  5. Create a pull request: Submit a pull request to the main Parsley.js repository, explaining your changes and addressing any feedback from maintainers. Follow the contribution guidelines provided in the repository’s documentation.

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.