Tuesday, June 30, 2015

validation with jQuery validation plugin

Here i am explaining how to do validation with jQuery validation plugin just go through it.

First of all you need to download Jquery library file and validate plugin library file.
Include script in your project like below
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>

Here is your Form

<form name="register" action="" method="post" >
Username: <input type="text" name="username" />
Email: <input type="text" name="email" />
Password: <input type="text" name="password" />
Confirm Password: <input type="text" name="password2" />
<input type="submit" name="submit" value="submit" />
</form>

<script>
$("#register").validate({
 
                rules: {
                    'username':{ required:true, remote: { url: 'http://webpersist.com/username_ajax.php',type: 'POST',}},
                    'email':{ required:true, email:true},
                    'password':{required:true,minlength:5},
                    'password2':{equalTo: "#password"},
                },
             
                messages: {
                  'username': {required:'Please enter username',remote:'Username already exist'},
                  'password':{required:'Please enter password',minlength:'Length should be greate than 5 character'},
                  'password1':{equalTo:'Confirm password should be same as password'},
                  'email':{required:'Please enter email',email:'email should be valid'},
                },
                errorPlacement: function(error, element) {
                     //Note : uncomment error according your html

                      error.appendTo(element.parent().next(".validation"));
                   // error.appendTo(element.parent().last(".validation"));
                   // error.appendTo(element.last(".validation"));
                  // error.appendTo(element.next(".validation"));
   },
                submitHandler: function(form) {
                 form.submit();   //it will load page
                //you can also use ajax here if you don't want to load page after submission of form
                // see below register function and use like bold if you want  register();  and comment form.submit();
                }
            });
</script>

Here is username_ajax.php file
<?php
$user_email = $_REQUEST;
$user_email = $user_email['users']['email'];
if (!empty($user_email))
{
$email = mysql_real_escape_string($user_email);
$query=mysql_query("SELECT * FROM `users` WHERE `email`='" . $user_email . "'");
 if (mysql_num_rows($query) > 0) {
            $valid = false;
  }
  else{
            $valid = true;
    }
header('Content-type: application/json');
echo json_encode($valid);
}
exit;
?>



//if you want to submit form with ajax use this function in submit handler instead of form.submit()
<script>
function register(){
    var serverurl = 'http://webpersist.com/';
    var data= $( "#register" ).serialize();
 
    $.ajax({
            type: "POST",
            url: serverurl+"register_ajax.php",
            data:data,
            success: function(res) {
           alert('Register succesfully);
    },
            error: function() { console.log("error"); }
    });

}
</script>

Handle custom error in your own div and hide error if everything is correct by using following functions.
   errorPlacement: function(error, element) {
             $('.validation').show();
             element.next(".validation").html(error.text());
 },
          success: function (element){
             
                element.next(".validation").hide();
            }

//if your field name is multi dimensional array  like below and you want to validate all fields then you need to user add rule.
<input type="text" name="data[Link][0][link]" placeholder="URL" />
<input type="text" name="data[Link][1][link]" placeholder="URL" />

$(document).on('click', 'button', function() {
            $("[placeholder=URL]").each(function () {
            $(this).rules("add", {
            required: true,
            url: true,
            remote: {url: 'links/url_check', type: 'POST'},
            messages: {
                required: "This field is required.",
                remote: "Sorry we can't accept this url."
},
} );
     
    });
 
    });

//you can use below jquery selector also to loop all fields but remember field name should be without index like <input type="text" name="data[Link][][link]" placeholder="URL" />

$('input[name="data[Link][\\][link]"]').each(function () {

if else condition in validation using depends function
"data[Campaign][text_message]":{
                    required:{
                       depends: function(element) {
                           if ($('#CampaignCampaignType2').is(':checked') || $('#CampaignCampaignType3').is(':checked')){
                               return true;
                           }else{
                               return false;
                           }
                       }
                    }
                }

Ignore hidden fields in forms
$("#postJobStep1").validate({
        ignore: "input[type='text']:hidden",
        errorElement: "div",
        errorClass: "cust_error",

Check image extension while uploading file
$("#BannerAdminAddForm").validate({

            ignore: "input[type='text']:hidden,input[type='file']:hidden",
            errorElement: "div",
            errorClass: "cust_error",
            rules: {
                    'data[Banner][image]': {
                    extension: "jpg|jpeg|png|gif"
                    }
            },
            messages: {
                'data[Banner][image]': {
                extension: "Please provide jpg,jpeg,png or gif only"
                },
            }
    });

Validation for dynamic added fields and check above field not same as below fields
$('#addRosterForm').submit(function(e) {
            $.each($('input' ,'#addRosterForm'), function(key) {
                if($(this).hasClass( "firstname" )){
                    $(this).rules("add", {
                        required: true,
                        lettersonly: true,
                        messages: {
                            required: "Please enter the first name.",
                            lettersonly: "Names can contain only alphabets."
                        }
                    });
                }
               
                if ($(this).hasClass('lastname')) {
                    $(this).rules("add", {
                        required: true,
                        lettersonly: true,
                        messages: {
                            required: "Please enter the last name.",
                            lettersonly: "Names can contain only alphabets."
                        }
                    });
                }
               
                if ($(this).hasClass('dob')) {
                    $(this).rules("add", {
                        required: true,
                        messages: {
                            required: "Please enter the dob."
                        }
                    });
                }
               
                if ($(this).hasClass('jersey')) {
                   
                    $(this).rules("add", {
                        required: true,
                        min:1,
                        maxlength:10,
                        messages: {
                            required: "Please enter the jersey number greater than 1.",
                            maxlength :"Please enter less than 10 characters jersey no"
                        }
                    });
                }
               
                if ($(this).hasClass('email')) {
                    var id = this.id;
                    $(this).rules("add", {
                        required: true,
                        email: true,
                        notEqualToGroup: ['.email'],
                        remote: {url: 'emailExist', type: 'POST',data: {email: function() {return $('#'+id).val();}}},
                        messages: {
                            required: "Please enter email.",
                            email :"Please enter valid email.",
                            remote :"Email already exist."
                        }
                    });
                }
            });
           
            e.preventDefault();

            // test if form is valid
            if($('#addRosterForm').validate().form()) {
                console.log("validates");
            } else {
                console.log("does not validate");
            }
           
       });

   jQuery.validator.addMethod("notEqualToGroup", function (value, element, options) {
    // get all the elements passed here with the same class
    var elems = $(element).parents('form').find(options[0]);
    // the value of the current element
    var valueToCompare = value;
    // count
    var matchesFound = 0;
    // loop each element and compare its value with the current value
    // and increase the count every time we find one
    jQuery.each(elems, function () {
        thisVal = $(this).val();
        if (thisVal == valueToCompare) {
            matchesFound++;
        }
    });
    // count should be either 0 or 1 max
    if (this.optional(element) || matchesFound <= 1) {
        //elems.removeClass('error');
        return true;
    } else {
        //elems.addClass('error');
    }
}, jQuery.format("Please enter a unique value."));



Validate image height width
https://jsfiddle.net/3fr8s9x7/39/

Note: also implement server side validation in registration function for security reason

Read More »