Easy PHP Form Validation with Parsley.js Library

On 4/25/2017

Hey! Let's see about easy php form validation using parsley.js jquery library. Form Validation should be done at both client and server side. For client validation you can use javascript or jquery and for server-side any backend script like PHP, Ruby etc. If your app consists of several web forms then validation process could be repetitive and boring. Here's where Parsley comes to the rescue.

Parsley is a light-weight javascript form validation library. With Parsley everything becomes easy. You can validate user input without writing lines and lines of code. Parsley uses special DOM API and includes all sorts of common validators you need to validate HTML forms. It's feature-rich and can be easily extended to accommodate custom validations.

How to Use Parsley to Validate HTML Forms?

For validating forms, you can configure all your validation rules right from DOM by using Parsley's data-parsley- DOM attribute.

Please note that the library relies on jquery so you must load jquery before loading Parsley.js.

Read Also:

Just download Parsley.js from here and move it to your application root. Load jquery & parsley in html form.

<html>
    <body>

        <form id="myform">
            ...
            ...
        </form>

        <script src="jquery.js"></script>
        <script src="parsley.min.js"></script>
    </body>
</html>

Then you must set validation rules to each one of the input fields. To make a field mandatory just use HTML5 required attribute or parsley's data-parsley-required.

<input id="myfield" type="text" required />

To validate an email field add Parsley DOM validator like this.

<input id="email" data-parsley-type="email" type="text" />

Validation error will be displayed below form input like this,

form validation parsley error

To match the input with specific pattern, say you need the field to contain only alphabets use data-parsley-pattern attribute like this.

<input id="name" type="text" data-parsley-pattern="^[a-zA-Z]+$" />

Finally you have to bind Parsley to the form. You can do this in two ways. First one is by simply adding data-parsley-validate attribute to html form tag.

<form id="myform" data-parsley-validate>
    ...
    ...
</form>

And the second one is to bind via java script function.

<form id="myform">
    ...
    ...
</form>

<script type="text/javascript">
    $('#myform').parsley();
</script>

PHP Form Validation with Parsley.js:

Now let's see a real world demo. For this I'm going to create user sign up form, validate fields with parsley.js and if everything went ok use php script to insert user details into mysql database. I'm using php here but it can be any other server-side script.

Create user registration form.

index.html

<!doctype html>
<html>
<head>
<title>User Registration Form</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <div class="col-xs-6 col-xs-offset-3 well">
            <form action="register.php" method="post" class="form-horizontal">
                <div class="form-group">
                    <div class="col-xs-6">
                        <label for="fname">First Name</label>
                        <input type="text" id="fname" name="fname" placeholder="Enter First Name" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                    <div class="col-xs-6">
                        <label for="lname">Last Name</label>
                        <input type="text" id="lname" name="lname" placeholder="Last Name" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="col-xs-12">
                        <label for="email">Email</label>
                        <input type="text" id="email" name="email" placeholder="Email" required data-parsley-type="email" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-12">
                        <label for="password">Password</label>
                        <input type="password" id="password" name="password" placeholder="Password" required data-parsley-length="[8, 16]" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-12">
                        <label for="cpassword">Confirm Password</label>
                        <input type="password" id="cpassword" name="cpassword" placeholder="Confirm Password"data-parsley-equalto="#password" data-parsley-trigger="keyup" required class="form-control" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-12">
                        <label for="cpassword">Website</label>
                        <input type="text" id="website" name="website" placeholder="Website URL" data-parsley-type="url" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-12">
                        <label>
                        <input type="checkbox" id="chkrules" name="chkrules" required /> I Accept the Terms & Conditions
                        </label>
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="col-xs-12">
                        <input type="submit" id="submit" name="submit" value="Register" class="btn btn-primary" />
                    </div>
                </div>
            </form>
        </div>
    </div>
    <script src="js/jquery-1.10.2.js"></script>
    <script src="js/parsley.min.js"></script>
    <script>
    $(document).ready(function(){
        $('form').parsley();
    });
    </script>
</body>
</html>

Then add php script to grab submitted form details and store it in database.

register.php

<?php
$con = mysqli_connect("localhost", "root", "", "mydemo") or die("Error " . mysqli_error($con));

if (isset($_POST['submit'])) {
    $firstname = mysqli_real_escape_string($con, $_POST['fname']);
    $lastname = mysqli_real_escape_string($con, $_POST['lname']);
    $emailid = mysqli_real_escape_string($con, $_POST['email']);
    $password = mysqli_real_escape_string($con, $_POST['password']);
    $website = mysqli_real_escape_string($con, $_POST['website']);
    $sql = "INSERT INTO tbl_users(fname, lname, email, password, website) VALUES('$firstname', '$lastname', '$emailid', 'md5($password)', '$website')";
    
    if(mysqli_query($con, $sql))
        echo "Successfully Registered!";
    else
        echo "Error! Please try again later!!!";
}
mysqli_close($con);
?>

And finally some css overriding. Parsley has its own css styling but since I have used bootstrap for form design I'm going to stick with it and override some bootstrap styles to color up the validation process.

CSS

.container {
    margin-top: 30px;
}

.well {
    background: none;
}

input.parsley-error,
select.parsley-error,
textarea.parsley-error {    
    border-color:#D43F3A;
    box-shadow: none;
}

input.parsley-error:focus,
select.parsley-error:focus,
textarea.parsley-error:focus {    
    border-color:#D43F3A;
    box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #FF8F8A;
}

input.parsley-success,
select.parsley-success,
textarea.parsley-success {    
    border-color:#398439;
    box-shadow: none;
}

input.parsley-success:focus,
select.parsley-success:focus,
textarea.parsley-success:focus {    
    border-color:#398439;
    box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #89D489
}

.parsley-errors-list {
    list-style-type: none;
    padding-left: 0;
    margin-top: 5px;
    margin-bottom: 0;
}

.parsley-errors-list.filled {
    color: #D43F3A;
    opacity: 1;
}

Done! We have everything in place. Now run the form and you will see something like this,

php form validation parsley jquery

Since form fields are set as required you will get validation error if you submit the form without providing input for mandatory fields.

php form validation error parsley

And the data-parsley-trigger="keyup" attribute will trigger field validation as soon as you key-in input fields.

php parsley form validation error

If a particular field validation is met then the input box will turn into green.

parsley form validation success

Once you input all the details and the parsley validation is successful, form will be submitted and the backend register.php script will take care of the rest of the registration process.

Well! I've shown really a gist of what parsley can do. We have only used a handful of built-in validators but the library supports lot more than that and also let you craft custom validators of your own. Here are some of the most common parsley validators you'll need for form validation.

API Validators Details
data-parsley-required Makes input field mandatory. Similar to HTML5 'required' attribute.
data-parsley-type="alphanum" Validates if input is a valid alpha-numeric string.
data-parsley-type="integer" Validates if input is a valid integer
data-parsley-pattern="^[a-zA-Z]+$" It validates if the input contains only alphabets. You can use any sort of regular expressions with '-pattern' attribute.
data-parsley-type="email" It validates if a form input is a valid email address
data-parsley-type="url" It validates if the input is a valid url.
data-parsley-length="[6, 12]" Validates if the length of the input is between minimum and maximum number of characters.
data-parsley-range="[6, 10]" Validates if the input is between the minimum and maximum range.
data-parsley-equalto="#somefield" It validates if value of the field matches with another field. This is quite useful in password confirmation type validation.
data-parsley-trigger="keyup" It triggers the validation process on key up event.

Parsley.js official site contains well-documented manual which you can use for learning more challenging functionalities. Once you get started it's quite easy to go with the flow. I hope you find this simple php form validation with parsley.js tutorial useful. Please don't forget to share it in social media. Meet you in another interesting tutorial.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *