Tuesday 17 January 2017

Jquery Validation

12:06 Posted by Nikesh No comments

Hi, Today we practice on validation from beginner to advanced.

First we will grab js file required files jquery.js and jquery.validate.min.js

Jquery has validate function where we can write rule for our controls and gives properties to validate and in case if it not validate we can write error messages.

lets create a basic validation code in jquery.

      <form name="validationform" id="validationform" action="thankspage.html" method="post">

Name: <input type="text" name="name" class="form-control">  <br/>
Email: <input type="email" name="email" class="form-control"/>  <br/>

<input type="submit" value="Submit" name="submit" />

</form>


<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>


<script>
$(document).ready(function(){

console.log('My Validation Start..');

$("#validationform").validate({
            rules: {                      //-----------------------Writing Rule in rules{} object.
  name: {      //----------------------Writing Conditions for controls.
required: true,
minlength: 2,
                               maxlength: 50
             },
                          email: {
                                 required: true,
                                 email: true
                                     }
                    },
            messages: {             //----------Writing messages for each conditions written above.
                            name: {
required: "Name is required gmgu",
minlength: "Minimum 2 required",
maxlength: "maximum 50"
         },
                             email: {
                                        required: "Email required",
                                         email: "Invalid Email-id"
                                    }
                            }
               });


});
</script>



In last we should apply some css 


<style type="text/css">

input.valid
    {
        border: solid 1px #00FF00;
    }

    input.error
    {
         border: solid 1px #FF0000;
    }
   
    label.error
{
color: #FF0000;
display: none;
font-size: 18px;
min-width: 150px;
text-align: left;
z-index: 4;
}
</style>





Now lets jump more ahead. Every day we write many javascript codes and got too many plugins js which some times become messy or get complex so we will go one more step ahead where we will write simple code which don't have connection with plugins and we can use only with jquery itself.

So for this we will validate a form field also we will go with asp.net page because also i am from this background you can also go with above html and it will work with data-vald attributes

So let's get started..

First i will go with asp.net write a form where you have controls:



@Html.TextBoxFor(m => m.Name, new { @name = "ContatName",data_vald = "N", @id = "Name", @class = "form-control", @maxlength = "250", @placeholder = "Enter Name" })
@Html.ValidationMessageFor(m => m.Name)



@Html.TextBoxFor(m => m.SchoolOrganization, new { @name = "SchoolOrganization", data_vald = "S", @id = "SchoolOrganization", @class = "form-control", @maxlength = "250", @placeholder = "School/Organization" })
 @Html.ValidationMessageFor(m => m.SchoolOrganization)
                                             
@Html.TextBoxFor(m => m.PhoneNumber, new { @name = "PhoneNumber", data_vald = "P", @class = "form-control", @id = "PhoneNumber", @maxlength = "15", @placeholder = "Enter Phone Number" })
@Html.ValidationMessageFor(m => m.PhoneNumber)

@Html.TextBoxFor(m => m.EmailId, new { @name = "EmailId", data_vald = "E", @id = "EmailId", @class = "form-control", @maxlength = "50", @placeholder = "Enter E-mail Id" })
@Html.ValidationMessageFor(m => m.EmailId)



Note:-  I am using data_vald for data-vald attribute of  html and giving his respective names.



Then we will write jquery functions as below



<script type="text/javascipt">

 $(function () {

/////////////On every controls change event writing a function which will check if no any input found in control and if no any validation error exist on page then add error message and customize its borders.
             
                $('#Name').change(function () {
                    if (!$('#Name').val()) {
                        if ($("#Name").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $('#Name').css('border', '1px solid #AC004A');
                            $("#Name").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Name is required*</div>");
                            //$('#Name').focus();
                            //return;
                        }
                    } else {
                        $("#Name").next(".field-validation-error").remove(); // remove it
                        $('#Name').css('border', '1px solid black');
                    }
                });


                $('#PhoneNumber').change(function () {
                    if (!$('#PhoneNumber').val()) {
                      
                 if ($("#PhoneNumber").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $('#PhoneNumber').css('border', '1px solid #AC004A');
                            $("#PhoneNumber").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Please Enter Phone*</div>");
                          //  $('#PhoneNumber').focus();
                          //  return;
                        }
                    } else {
                        $("#PhoneNumber").next(".field-validation-error").remove(); // remove it
                        $('#PhoneNumber').css('border', '1px solid black');
                    }
                });
                $('#EmailId').change(function () {
                    debugger;

                    $("#EmailId").next(".field-validation-error").remove(); // remove it
                    $('#EmailId').css('border', '1px solid black');

                    if (!$('#EmailId').val()) {
                        if ($("#EmailId").next(".field-validation-error").length == 0) // only add if not added
                        {

                            $('#EmailId').css('border', '1px solid #AC004A');
                          //  $("#EmailId").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                         //   $('#EmailId').focus();
                          //  return;
                        }
                    } else {

                        if (validateEmail($('#EmailId').val())) {
                           // $("#EmailId").next(".field-validation-error").remove(); // remove it
                            $('#EmailId').css('border', '1px solid black');
                        }
                        else {
                            $('#EmailId').css('border', '1px solid #AC004A');
                            // $("#EmailId").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                        }

                     
                    }
                });

                $('#SchoolOrganization').change(function () {
                  

                    $("#SchoolOrganization").next(".validation").remove(); // remove it
                    $('#SchoolOrganization').css('border', '1px solid black');

                    if (!$('#SchoolOrganization').val()) {
                        if ($("#SchoolOrganization").next(".SchoolOrganization").length == 0) // only add if not added
                        {
                            $('#SchoolOrganization').css('border', '1px solid #AC004A');
                            //  $("#EmailId").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                            //   $('#EmailId').focus();
                            //  return;
                        }
                    } else {

                        if (validateEmail($('#SchoolOrganization').val())) {
                            $("#SchoolOrganization").next(".validation").remove(); // remove it
                            $('#SchoolOrganization').css('border', '1px solid black');
                        }
                        else {
                            $('#SchoolOrganization').css('border', '1px solid #AC004A');

                        }


                    }
                });




////After completing  each we will write validation function which can occur after form submit.


 function checkMandatoryFields(e) {
               
//// For this i am going to create an array which can store my data-vald attributes in array and from there i can loop and check which field was not valid values.

                          
                var validationcontent = [];

/////////////Emptying array before adding values.//////////////////
                for (var i = validationcontent.length; i > 0; i--) {

                    validationcontent.pop();

                }
Check for each controls validity and in case of not valid push that too validationcontent array.
So we can check their data-vald values and based on that update messages.


Checking each controls validity separately 


                if (!$('#BillingName').val()) {
                    validationcontent.push($('#BillingName').attr('data-vald'))
                }
                if (!$('#PhoneNumber').val()) {
                    validationcontent.push($('#PhoneNumber').attr('data-vald'))
                } if (!$('#EmailId').val()) {
                    validationcontent.push($('#EmailId').attr('data-vald'))
                } if (!$('#SchoolOrganization').val()) {
                    validationcontent.push($('#SchoolOrganization').attr('data-vald'))
                }

Loop through validationcontent and based on their values show messages for them

                for (var i = 0, len = validationcontent.length; i < len; i++) {
                    var s = validationcontent[i];
                    if (s == 'N') {
                   if ($("#Name").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $('#Name').css('border', '1px solid #AC004A');
                            $("#Name").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Name is required*</div>");
                           
                         
                        }
                        else {
                           $("#BillingName").next(".field-validation-error").remove(); // remove it
                            $('#BillingName').css('border', '1px solid black');

                        }
                    }
                    if (s == 'S') {
                        if ($("#SchoolOrganization").next(".validation").length == 0) // only add if not added
                                {
                                    $('#SchoolOrganization').css('border', '1px solid #AC004A');                                   
                                    $("#SchoolOrganization").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>School/Organization Name is required*</div>");
                                 
                                }
                            else {
                               $("#SchoolOrganization").next(".validation").remove(); // remove it
                                $('#SchoolOrganization').css('border', '1px solid black');
                            }
                    }
                    if (s == 'P') {
                        if ($("#PhoneNumber").next(".field-validation-error").length == 0) // only add if not added
                                {
                                    $('#PhoneNumber').css('border', '1px solid #AC004A');
                                    $("#PhoneNumber").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Please Enter Phone*</div>");
                                  
                          
                        }
                        else {
                               $("#PhoneNumber").next(".field-validation-error").remove(); // remove it
                                $('#PhoneNumber').css('border', '1px solid black');
                           }
                    }
                    if (s == 'E') {
                        if ($("#EmailId").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $("#EmailId").next(".field-validation-error").remove();
                                    $('#EmailId').css('border', '1px solid #AC004A');
                                    $("#EmailId").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                                   
                           
                        }
                        else {
                            $("#EmailId").next(".field-validation-error").remove(); // remove it
                               $('#EmailId').css('border', '1px solid black');
                           }
                    }
               
                }

After alerting return so that we can stop posting of form

                if (validationcontent.length != 0) {
                    return;
                }
       }
}




0 comments:

Post a Comment