Written by: Geoffrey Callaghan

Parsley.js tutorial

Parsley.Js Tutorial

Parsley.js is a lightweight and powerful JavaScript library that helps you validate forms on the client side. It provides a simple way to add validation rules and messages to your forms. This tutorial will guide you through the basics of using Parsley.js.

Step 1: Setup Your Project

To get started, you need to include Parsley.js in your project. You can either download the library from the official website or use a CDN.

Using a CDN

Include the following lines in the <head> section of your HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Parsley.js Example</title>
  <!-- Parsley CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.9.2/parsley.css">
  <!-- Parsley JS -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.9.2/parsley.min.js"></script>
</head>
<body>
  <!-- Your HTML content here -->
</body>
</html>

Step 2: Basic Usage

Let’s create a simple form and add Parsley.js validation to it.

  1. Create a form in your HTML file:
<body>
  <div class="container">
    <h1>Parsley.js Form Validation Example</h1>
    <form id="example-form">
      <div>
        <label for="name">Name</label>
        <input type="text" id="name" name="name" required data-parsley-maxlength="15" data-parsley-required-message="Name is required" data-parsley-maxlength-message="Name must be 15 characters or less">
      </div>
      <div>
        <label for="email">Email</label>
        <input type="email" id="email" name="email" required data-parsley-type="email" data-parsley-required-message="Email is required" data-parsley-type-message="Invalid email address">
      </div>
      <button type="submit">Submit</button>
    </form>
  </div>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      $('#example-form').parsley();
    });
  </script>
</body>
  1. Initialize Parsley.js for the form:

Add the following script at the end of your HTML file or within a <script> tag in the <head> section:

document.addEventListener('DOMContentLoaded', function() {
  $('#example-form').parsley();
});

Step 3: Adding Custom Validation Rules

You can create custom validation rules with Parsley.js.

  1. Define a custom rule:
Parsley.addValidator('noAdmin', {
  requirementType: 'string',
  validateString: function(value, requirement) {
    return value !== requirement;
  },
  messages: {
    en: 'Username cannot be "admin"'
  }
});
  1. Use the custom rule in your form:
<div>
  <label for="username">Username</label>
  <input type="text" id="username" name="username" required data-parsley-no-admin="admin">
</div>

Step 4: Customizing Error Messages

Parsley.js allows you to customize the error messages for validation rules.

  1. Customizing messages for individual fields:

You can add data attributes to your input fields to customize error messages.

<div>
  <label for="password">Password</label>
  <input type="password" id="password" name="password" required minlength="6" data-parsley-required-message="Password is required" data-parsley-minlength-message="Password must be at least 6 characters long">
</div>
  1. Customizing global messages:

You can set global error messages by extending the default Parsley messages.

Parsley.addMessages('en', {
  defaultMessage: "This value seems to be invalid.",
  type: {
    email:        "This value should be a valid email.",
    url:          "This value should be a valid url.",
    number:       "This value should be a valid number.",
    integer:      "This value should be a valid integer.",
    digits:       "This value should be digits.",
    alphanum:     "This value should be alphanumeric."
  },
  notblank:       "This value should not be blank.",
  required:       "This value is required.",
  pattern:        "This value seems to be invalid.",
  min:            "This value should be greater than or equal to %s.",
  max:            "This value should be lower than or equal to %s.",
  range:          "This value should be between %s and %s.",
  minlength:      "This value is too short. It should have %s characters or more.",
  maxlength:      "This value is too long. It should have %s characters or fewer.",
  length:         "This value length is invalid. It should be between %s and %s characters long.",
  mincheck:       "You must select at least %s choices.",
  maxcheck:       "You must select %s choices or fewer.",
  check:          "You must select between %s and %s choices.",
  equalto:        "This value should be the same."
});

Parsley.setLocale('en');

Step 5: Handling Form Submission

You can handle form submission using JavaScript.

<script>
document.addEventListener('DOMContentLoaded', function() {
  $('#example-form').parsley().on('form:submit', function() {
    alert('Form is valid and ready to be submitted!');
    // Perform your form submission tasks here
    return false; // Prevent default form submission
  });
});
</script>

Conclusion

Parsley.js is a powerful and easy-to-use library for form validation in JavaScript. It provides a wide range of built-in validation rules and allows you to create custom rules and error messages. This tutorial covers the basics, but Parsley.js offers many more features that you can explore in its official documentation.