Today I came with another jQuery article guys! Have you seen validations when you are trying to sign up or login to a site? Without submitting your data? This is the simplest way to do it. As you have seen in web sites, there are two types of validations basically. They are front end and back end. Front end means your input details are validated real time while you are typing and without a submission. As an example, think you have entered an email with an invalid format. When you are trying input next data, error message is shown for the previous invalid input on the frond end user interface. Back end means, your inputs are validated after a submission through a button click. It is not much user friendly because if a user has entered wrong inputs for several times, he or she will have to submit again and again and get the corrected data, to get registered in a site.
This jQuery plugin does the job for you. Real time front end validation is done through this plugin. Let's see how to get the benefit of this plugin. Here I will use Codeigniter framework for PHP and Bootstrap framework for styling. This is a short demo of the application what will we build today. Watch it!
First create a project folder and put the codeigniter files into it.
If you are not familiar with Codeigniter, this will be difficult. Refer my Codeigniter articles here to learn the framework.
Download Source Code : jQuery-Form-Validation
As usual, a database is required for this. So, create a database called validation. You can give any name you want. So basic configurations are like this.
Project folder => jQueryForm
Base URL => $config['base_url'] = 'http://localhost/jQueryForm/
Database name => validation
Database table name => users
Autoload libraries => database
Autoload helpers => form , url
Default Controller => Register
Import the SQL file called validation.sql in my GitHub folder to get create the database.
We have to create the view file first. For that go into the applications/views folder and create a view called signup.php.
In this view we are going to link validation plugin through a JS file. Visit the below site to get the source file.
https://github.com/jquery-validation/jquery-validation/releases/tag/1.17.0
Or otherwise you can include the CDN
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js
Include this JS file just before the ending body tag of the view as I have done below. Configuration is explained after this code.
<!DOCTYPE html>
<html>
<head>
<title>jQuery Validation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Bootstrap CSS styles -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Roboto Google font -->
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<!-- Google jQuery CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Custom CSS -->
<style type="text/css">
body {
font-family: 'Roboto', sans-serif;
}
label {
font-size: 16px;
}
.error {
color: #a94442;
border-color: #a94442;
margin-top: 10px;
}
.panel {
border: 1px solid;
border-color: black;
}
</style>
</head>
<body>
<div class="col-lg-12">
<div class="col-lg-4"></div>
<div class="col-lg-4">
<h2 style="margin-top: 30px;text-align: center;">jQuery Form Validation</h2>
<br>
<div class="panel panel-default">
<div class="panel-heading">
<br>
<h3 class="panel-title text-center">Fill the form to sign up</h3>
<br>
</div>
<div class="panel-body">
<!-- success message to be displayed after adding a user to the database successfully -->
<?php if($this->session->flashdata('success')): ?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<?php echo $this->session->flashdata('success');?>
</div>
<?php endif; ?>
<!-- Form -->
<?php echo form_open('Register/signUp', array('id' => 'signup-form','method' => 'POST'));?>
<div class="form-group">
<label>Username</label>
<br>
<input type="text" id="username" name="username" class="form-control">
<br>
<!-- validation message for username checking with database -->
<?php echo validation_errors('<div style="color: #a94442;font-weight: bold;font-size: 16px;"><p>','</p></div>'); ?>
</div>
<div class="form-group">
<label>Email</label>
<br>
<input type="email" id="email" name="email" class="form-control" placeholder="">
<br>
</div>
<div class="form-group">
<label>Password</label>
<br>
<input type="password" id="password" name="password" class="form-control" placeholder="">
<br>
</div>
<div class="form-group">
<label>Confirm Password</label>
<br>
<input type="password" id="cpassword" name="cpassword" class="form-control" placeholder="">
<br>
</div>
<input type="submit" class="btn btn-primary" value="Sign Up">
<br>
<?php echo form_close();?>
</div>
</div>
</div>
<div class="col-lg-4"></div>
</div>
<!-- validation plugin configuration -->
<script type="text/javascript">
// wait untill the page is loaded completely
$(document).ready(function(){
// include the validation for the form function comes with this plugin
$('#signup-form').validate({
// set validation rules for input fields
rules: {
username: {
required : true,
minlength: 5
},
email: {
required : true,
email: true
},
password: {
required : true,
minlength: 5
},
cpassword: {
required : true,
equalTo: "#password"
}
},
// set validation messages for the rules are set previously
messages: {
username: {
required : "Username is required",
minlength: "Username must contain at least 5 characters"
},
email: {
required : "Email is required",
email: "Enter a valid email. Ex: example@gmail.com"
},
password: {
required : "Password is required",
minlength: "Password must contain at least 5 characters"
},
cpassword: {
required : "Confirm Password is required",
equalTo: "Confirm Password must be matched with Password"
}
}
});
});
</script>
<!-- Bootstrap JS file -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- Validation JS file -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
</body>
</html>
Validation Plugin Configuration
You can see a new script tag at the end of the file. I'm going to explain it.
First we have to load the jQuery function to wait until the page loading. Then we include the validation function comes with plugin. For this, an ID or a CLASS selector is needed for the signup form. Here I use an ID called signup-form. Next step is including validation rules for the inputs. They are defined in this plugin. Those rules can be set any order. For one input, several rules can be included.
Rules
Format:
input field name {
rule 1 : value 1,
rule 2 : value 2
}
required : true - Without this field, form can not be submitted
minlength : 5 - Requires at least 5 characters
email: true - Checks the email is with the standard email format
equalTo : "#password"
- Checks this input is same as another input
Ex: Confirm password and Password
Messages
Now we have to set validation messages that are displayed when a user input a wrong/invalid value for each input field.
Format:
input field name {
rule 1 : message 1,
rule 2 : message 2
}
These messages can be set as you want. But remember to set a proper and matching message for each input. Otherwise the user will get an wrong idea about the error of the entered input!
CSS for validation messages
When a user entered a wrong input, a label tag is automatically generated after the input field with a class called error. You can check it in the browser console->elements. That's why I included a styling for a class named error, in the custom styles.
Styles for error class
.error {Styles for error class
color: #a94442;
border-color: #a94442;
margin-top: 10px;
}
I think now you have got the idea of including validation plugin. Next part is making the controller and the model to get a user registered.
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Register extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Register_model');
}
public function index()
{
$this->load->view('signup');
}
public function signUp()
{
// username availability is checcked after submission
$this->form_validation->set_rules('username', 'Username', 'trim|is_unique[users.username]');
if ($this->form_validation->run() == TRUE) {
$data = array(
//assign user data into array elements
'username' => $this->input->post('username'),
'email' =>$this->input->post('email'),
'password' =>sha1($this->input->post('password'))
);
$this->Register_model->insertUser($data);
//set message to be shown when registration is completed
$this->session->set_flashdata('success','User is registered!');
redirect('Register/Signup');
} else {
//return to the signup page again with validation errors
$this->load->view('signup');
}
}
}
Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Register_model extends CI_Model {
public function insertUser($data)
{
// insert data to the database
$this->db->insert('users', $data);
}
}
All the explanations are included in the files as comments. Read them for your understanding. After this step, you have completed this application! Now it's the time to check. Hit the URL in browser and check whether the validations you have set are working or not. That's all. Now I'm concluding this article..
Wait for the next article guys!
Good Bye!
Form Validation using jQuery validation plugin
Reviewed by DAL
on
January 10, 2018
Rating:
No comments: