Form Validation Using Jquery

The code that every web developer looking for. Validating a form in all possible ways. A simple and effective code is here. 

Here we are validating all common input types which we use in register form like name, email, phone, password, radio button, select option.

Includes

    <link rel="stylesheet" href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>



Script

<script>
function Validate() {

(function ($) {

 jQuery.validator.setDefaults({
       errorPlacement: function (error, element) {
            error.appendTo('#invalid-' + element.attr('id'));
       }
});

//To validate letters

$.validator.addMethod("letters", function (value, element) {
   return this.optional(element) || value == value.match(/^[a-zA-Z\s]*$/);
});



//To validate Number
$.validator.addMethod("number", function (value, element) {
      return this.optional(element) || value == value.match(/^[0-9]*$/);
});

//To validate digits for phone number that should start with only 7 or 8 or 9
$.validator.addMethod("digits", function (value, element) {
    return this.optional(element) || value == value.match(/^^[789]\d{9}$/);
});

//To validate password
$.validator.addMethod("pwcheckNumber",
   function (value, element) {
   return /\d/.test(value);
});

$.validator.addMethod("pwcheckUppercase",
   function (value, element) {
   return /[A-Z]/.test(value);
});

$.validator.addMethod("pwcheckSpecial",
     function (value, element) {
     return /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/.test(value);
});

//Form validation
$("#Form").validate({
                    
rules: {

Title: {
     required: true,                  
},

FirstName: {
   required: true,
   minlength: 3,
   letters: true                      
},

Mobile: {
    required: true,
    number: true,
    minlength: 10,
    maxlength: 10,
    digits: true                      
},

Email: {
    required: true,
    email: true,
},

Password: {
     required: true,
     minlength: 8,
     pwcheckNumber: true,
     pwcheckUppercase: true,
     pwcheckSpecial: true,          
},

ConfirmPassword: {
     required: true,
     equalTo: "#Password"                   
},

Gender: {
     required: true,
}
     
},

//Message suggestions that you see on screen     
messages: {

Title: {
       required: "Please select title",
},

FirstName: {
      required: "Please enter first name",
      minlength: "Name should be minimum 3 characters",
      letters: "Only letters and spaces are allowed",                              
},

Mobile: {
       required: "Please enter  phone number",
       minlength: "Please enter valid phone number",
       maxlength: "Please enter valid phone number",
       digits: "Phone number should be start with 789", 
},

Email: {
      required: "Please enter email",
      minlength: "Please enter a valid email address",
},

Password: {
       required: "Please enter password",
       minlength: "Password must be minmum 8 character",
       pwcheckNumber: "Password must contains one digit",
       pwcheckUppercase: "Password must contains atleast one uppercase letter",
       pwcheckSpecial: "Password must contains atleast one special character",
},

ConfirmPassword: {
       required: "Please enter confirm password ",
       equalTo: "Confirm password must same as password",
},

Gender: {
       required: "Please select gender type"                     
}
}

});
})($);
}
</script>

//CSS
<style>
.error_msg {
        color: red;
}

body{
        position: absolute;
        width: 600px;
        height: 200px;
        z-index: 15;
        top: 15%;
        left: 30%;
        margin: -100px 0 0 -150px;
     }

.box-header{
        background: #dc3545;
        width: 500px;
        height: auto;
text-align: center;
        color: white;
        font-size: 30px;
        padding: 10px;
    }

.box{
        background: #43c181;
        padding-top: 10px;
        padding-left: 110px;
        padding-bottom: 30px;
        width: 500px;
        height: auto;
    }
</style>




<body onload="Validate()">

<div class="box-header">Register From</div>

<div class="box">

    <form action='#' method='post' id='Form' enctype='multipart/form-data'>
        <div class="col-md-8">
            <label>Title</label>
            <select id="Title" name="Title" class="form-control">
                <option value="">Select Title</option>
                <option value="Mr.">Mr.</option>
                <option value="Mrs.">Mrs.</option>
                <option value="Ms.">Ms.</option>
                <option value="Mss.">Mss.</option>
                <option value="Dr.">Dr.</option>
            </select>
            <div id="invalid-Title" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>First Name</label>
            <input type="text" id="FirstName" name="FirstName" class="form-control"
                   placeholder="First Name"/>
            <div id="invalid-FirstName" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Mobile</label>
            <input type="text" id="Mobile" name="Mobile" class="form-control" placeholder="Mobile">
            <div id="invalid-Mobile" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Email</label>
            <input type="text" id="Email" name="Email" class="form-control" placeholder="Email">
            <div id="invalid-Email" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Password</label>
            <input type="password" id="Password" name="Password" class="form-control"
                   placeholder="Password"/>
            <div id="invalid-Password" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Confirm Password</label>
            <input type="password" id="ConfirmPassword" name="ConfirmPassword" class="form-control"
                   placeholder="ConfirmPassword"/>
            <div id="invalid-ConfirmPassword" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Gender</label>
            <input type="radio" id="Gender" name="Gender" value="Male"> Male
            <input type="radio" id="GenderNew" name="Gender" value="Female"> Female<br>
            <div id="invalid-Gender" class="error_msg"></div>
        </div>

        <div class="col-md-12" align="center">
            <input type="submit" value="Submit" class="btn btn-danger" id="Submit" name="Submit"
                   onclick="Register()">
        </div>
    </form>

</div>

</body>


Result



*Please share, comment and subscribe to PHP Javascript for more.

Display JSON data in dropdown

Display JSON data in a table



How to populate JSON data in input fields using Javascript in a best way?

Here we are discussing about how to populate JSON data in HTML input fields dynamically.This might be the best way to work on any kind of edit data/form operation.

Steps

1. Creating database and table
2. Connecting to database
3. Fetching data
4. Parsing data
5. Populating in the form

Creating database and table

Create a database(demo) make sure that you are using the right database name in your config.php file.

Run the following queries to create a table with some sample data


To create a table(user) 

CREATE TABLE `user` (
  `UserID` int(12) NOT NULL,
  `FirstName` varchar(48) NOT NULL,
  `LastName` varchar(48) NOT NULL,
  `Email` varchar(128) NOT NULL,
  `Password` varchar(20) NOT NULL,
  `City` varchar(48) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

To insert data into the table

INSERT INTO `user` (`UserID`, `FirstName`, `LastName`, `Email`, `Password`, `City`) VALUES
(7, 'Rahul', 'Rajshekaran', 'Rahul@zzz.xxx', 'Rahul@123', 'Pune'),
(8, 'Mahesh', 'Krishna', 'Mahesh@xxx.xxx', 'Mahesh@123', 'Delhi'),
(9, 'Mahidar', 'kumar', 'Mahidar@xxx.com', 'Mahidar@123', 'Pune'),
(10, 'Mahpal', 'yadhav', 'mahipa@xxx.com', 'Mahipa@123', 'Delhi');



Connecting to database(config.php)


<?php
/* Database connection start */
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'root';
$dbName = 'demo';

//Create connection and select DB
$connection = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($connection->connect_error){
die("Unable to connect database: " . $connection->connect_error);
}
?>


Fetching data(index.php)


<?php
include('config.php');
//Check UserID set or not
if (isset($_GET['UserID'])) {
    $UserID = $_GET['UserID'];
    $sql = "SELECT * FROM user WHERE UserID='$UserID'";
    $result = mysqli_query($connection, $sql);
    if ((mysqli_num_rows($result)) > 0) {
        while ($row = mysqli_fetch_array($result)) {
            extract($row);
            $rows[] = array("Message" => "Success", "UserID" => $UserID, "FirstName" => $FirstName, "LastName" => $LastName, "Email" => $Email, "City" => $City);
        }
    } else {
        $rows[] = array("Message" => "No Data");
    }
} else {
    $rows[] = array("Message" => "Error");
}
echo json_encode($rows);
mysqli_close($connection);
?>



Parsing data with JQuery


//Script
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
function userEdit(UserID) {
    $(document).ready(function () {
        $.getJSON("http://localhost/demo/user.php?UserID=" + UserID,
            function (json) {
                for (var i = 0; i < json.length; i++) {
var Message = json[i].Message;
document.getElementById("Message").innerHTML = Message;
                    $.each(json[0] , function (key, value){
                        $('input[id='+key+']').val(value);
                    });
                }
            });
    });
}
</script>
//CSS
<style type="text/css">
    body{
        position: absolute;
        width: 600px;
        height: 200px;
        z-index: 15;
        top: 40%;
        left: 30%;
        margin: -100px 0 0 -150px;
    }
    .box{
        background: #43c181;
        padding-top: 10px;
        padding-left: 60px;
        padding-bottom: 30px;
        width: 500px;
        height: auto;
    }
    .btn-success{
        padding: 5px;
    }
</style>


*Place the above code in the head section of your HTML.

Populating in the form


<body>

<div class='box'>

<h4 id="Message"></h4>

<form action='#' method='post' id='Form' enctype='multipart/form-data'>

<div class="col-md-10">
            <label>First Name</label>
            <input type="text" id="FirstName" class="form-control" name="FirstName" placeholder='First Name'/>
        </div>

 <div class="col-md-10">
            <label>Last Name</label>
            <input id="LastName" name="LastName" class="form-control" type="text" placeholder='Last Name'/>
        </div>

 <div class="col-md-10">
            <label>Email</label>
            <input id="Email" name="Email" class="form-control" type="text"
                   placeholder='Email'/>
        </div>

</form>

</div>

</body>

//Call function
<script>
userEdit(UserID = 7);
</script>


Result


*Please subscribe to PHP Javascript for more.

* Display JSON data in dropdown

Display JSON data in a table


Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts