Front end form validation with Parsley

December 1, 2015

Screen Shot 2015-11-28 at 7.33.35 PM

Front end validation for your forms is a must have these days! It’s not a good user experience to reload the page after the user hits submit, just to find an error and send them back to the same page! Even worse is if you didn’t store their original entries, forcing them to re-enter even the fields they did get right!

Fortunately, there are all sorts of great, free and open source libraries to make front end validation a breeze. Today we’re going to check out Parsley.js.

Installation

First, we’ll head over to http://parsleyjs.org/doc/download.html and download parsley.min.js. Then we’ll create a new project that looks something like this:

<html>
  <head>
      <title>Front End Validation</title>
  </head>
  <body>
    <form id="myForm" action="your_server" method="post">
      <input id="name" name="username" type="text" placeholder="Username" />
      <input id="email" name="email" type="text" placeholder="Email" />
      <input type="submit" value="Submit" />
    </form>
    <script src="js/parsley.min.js"></script>
  </body>
</html>

Next, we’ll add data-parsley-validate=“” to the form and then we’re ready to validate!

<html>
  <head>
    <title>Front End Validation</title>
  </head>
  <body>
    <form id="myForm" action="your_server" method="post"data-parsley-validate="">
      <input id="name" name="username" type="text" placeholder="Username" />
      <input id="email" name="email" type="email" placeholder="Email" />
      <input type="submit" value="Submit" />
    </form>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="js/parsley.min.js"></script>
    <script>
      $("#myForm").on('submit', function(e) {
        const $form = $(this);

        e.preventDefault();

        $form.parsley().validate();

        if ($form.parsley().isValid()) {
          $form.get(0).submit();
        }
      });
    </script>
  </body>
</html>

 

When a user tries to submit the form, it will first handle basic validation, making sure the fields aren’t empty and also that the field with type set to email validates as an email address.

Then, assuming the validation passes, we force the form to actually submit.