Thursday 6 September 2018

Client Side Form Validation using Parsley.js with PHP Ajax



Validation of Form Data is a very time consuming task of any web developer. So, for reduce form validation task here we have make this tutorial in which we have describe PHP form validation by using Parsleys.js jQuery library. If you are web developer then you have know form validation has been done at server side and client side also or both side. At client side form validation we mainly use pure javascript or jQuery script and on server side form data validation we have used scripting language like PHP. If you have developed some big web application with multiple forms, then you have to write form validation code for each form and this form validation task will be boring and without form validation web application will not work properly and cannot give proper output of any task. Because if wrong type of data entered into system then will also give wrong output. So, Form validation is very required task in web application development.

For this form validation here we have use Parsleys.js Library has been use with PHP form for validate form data at client side. Parsley is a simple and light weight javascript library mainly for form validation. By using this library we can validate form data very easily and it will validate HTML input fields data without writing any lines of code. This form validation Library mainly use special DOM API with attribute for validate HTML form data. That validation are feature rich and we can easily implement into our form and also make some custom validation also.

Below you can find simple example of HTML form validation has been done by using Parsley.js with Ajax and PHP.










Source Code


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_register`
--

CREATE TABLE `tbl_register` (
  `register_id` int(11) NOT NULL,
  `first_name` varchar(150) NOT NULL,
  `last_name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL,
  `website` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_register`
--
ALTER TABLE `tbl_register`
  ADD PRIMARY KEY (`register_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_register`
--
ALTER TABLE `tbl_register`
  MODIFY `register_id` int(11) NOT NULL AUTO_INCREMENT;


index.php



<html>  
    <head>  
        <title>PHP Form Validation using Parsleys.js Library</title>  
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <script src="http://parsleyjs.org/dist/parsley.js"></script>
    </head>
 <style>
 .box
 {
  width:100%;
  max-width:600px;
  background-color:#f9f9f9;
  border:1px solid #ccc;
  border-radius:5px;
  padding:16px;
  margin:0 auto;
 }
 input.parsley-success,
 select.parsley-success,
 textarea.parsley-success {
   color: #468847;
   background-color: #DFF0D8;
   border: 1px solid #D6E9C6;
 }

 input.parsley-error,
 select.parsley-error,
 textarea.parsley-error {
   color: #B94A48;
   background-color: #F2DEDE;
   border: 1px solid #EED3D7;
 }

 .parsley-errors-list {
   margin: 2px 0 3px;
   padding: 0;
   list-style-type: none;
   font-size: 0.9em;
   line-height: 0.9em;
   opacity: 0;

   transition: all .3s ease-in;
   -o-transition: all .3s ease-in;
   -moz-transition: all .3s ease-in;
   -webkit-transition: all .3s ease-in;
 }

 .parsley-errors-list.filled {
   opacity: 1;
 }
 
 .parsley-type, .parsley-required, .parsley-equalto{
  color:#ff0000;
 }
 
 </style>
    <body>  
        <div class="container">  
            <br />  
            <br />
   <br />
   <div class="table-responsive">  
    <h3 align="center">PHP Form Validation using Parsleys.js Library</h3><br />
    <div class="box">
     <form id="validate_form">
      <div class="row">
       <div class="col-xs-6">
        <div class="form-group">
         <label>First Name</label>
         <input type="text" name="first_name" id="first_name" placeholder="Enter First Name" required data-parsley-pattern="^[a-zA-Z]+$" data-parsley-trigger="keyup" class="form-control" />
        </div>
       </div>
       <div class="col-xs-6">
        <div class="form-group">
         <label>Last Name</label>
         <input type="text" name="last_name" id="last_name" placeholder="Last Name" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" class="form-control" />
        </div>
       </div>
      </div>
      <div class="form-group">
       <label for="email">Email</label>
       <input type="text" name="email" id="email" placeholder="Email" required data-parsley-type="email" data-parsley-trigger="keyup" class="form-control" />
      </div>
      <div class="form-group">
       <label for="password">Password</label>
       <input type="password" name="password" id="password" placeholder="Password" required data-parsley-length="[8, 16]" data-parsley-trigger="keyup" class="form-control" />
      </div>
      <div class="form-group">
       <label for="cpassword">Confirm Password</label>
       <input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password"data-parsley-equalto="#password" data-parsley-trigger="keyup" required class="form-control" />
      </div>
      <div class="form-group">
       <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 class="form-group">
       <div class="checkbox">
        <label><input type="checkbox" id="check_rules" name="check_rules" required /> I Accept the Terms & Conditions</label>
       </div>
      </div>
      <div class="form-group">
       <input type="submit" id="submit" name="submit" value="Submit" class="btn btn-success" />
      </div>
     </form>
    </div>
   </div>  
  </div>
    </body>  
</html>  
<script>  
$(document).ready(function(){  
    $('#validate_form').parsley();
 
 $('#validate_form').on('submit', function(event){
  event.preventDefault();
  if($('#validate_form').parsley().isValid())
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:$(this).serialize(),
    beforeSend:function(){
     $('#submit').attr('disabled','disabled');
     $('#submit').val('Submitting...');
    },
    success:function(data)
    {
     $('#validate_form')[0].reset();
     $('#validate_form').parsley().reset();
     $('#submit').attr('disabled',false);
     $('#submit').val('Submit');
     alert(data);
    }
   });
  }
 });
});  
</script>


action.php



<?php

//action.php

sleep(5);

if(isset($_POST['first_name']))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 
 $data = array(
  ':first_name'  => $_POST['first_name'],
  ':last_name'  => $_POST['last_name'],
  ':email'   => $_POST['email'],
  ':password'   => $_POST['password'],
  ':website'   => $_POST['website']
 );
 
 $query = "
 INSERT INTO tbl_register 
 (first_name, last_name, email, password, website) 
 VALUES (:first_name, :last_name, :email, :password, :website)
 ";
 $statement = $connect->prepare($query);
 if($statement->execute($data))
 {
  echo 'Registration Completed Successfully...';
 }
}

?>

9 comments:

  1. how to hash password? which is the most secure way?

    ReplyDelete
  2. I want when i click on submit it take me on another page how can i do it? please

    ReplyDelete
  3. sir how to check if email alerady exists in database with parsely js with Parsley custom remote validate

    ReplyDelete
  4. Hi

    Thanks for article.

    How can I add redirect if statement is correct?

    Thanks

    ReplyDelete
  5. how to create sweetalert replacing alert message and download pdf file after sweetalert message completion

    ReplyDelete
  6. how to validate both server-side and client side with ajax

    ReplyDelete