Jquery Form Validation

In Every project Form validation is a basic need. So Here I am going to write a complete script function of jquery validations. I have written a number of custom methos for validating fields which are not there in the jquery library but often they are used in our project.

Requirements:

@ jquery.validate.js- you can find jquery validation file on http://jqueryvalidation.org/
@ jquery.min.js- you can find jquery library on https://jquery.com/download/
You can directly give the cdn path of these files or you can include in footer of your project after downloading.

Here is a complete example function of how to use this library.

Customvalidations.js

$(document).ready(function(){
    
    //adding cutom methods    
     jQuery.validator.addMethod("lettersnumberspacedotandbracket", function(value, element) {
	return this.optional(element) || /^[0-9a-zA-Z.,\/_\-()'"\s]+$/i.test(value);
    }, "Enter only alphabets, numbers or punctuation.");
    
     //adding cutom methods    
     jQuery.validator.addMethod("lettersnumberspacedotandbracketquestion", function(value, element) {
	return this.optional(element) || /^[0-9a-zA-Z.,()?'"\s]+$/i.test(value);
    }, "Enter only alphabets, numbers or punctuation.");
    
    jQuery.validator.addMethod("checkurl", function(value, element){
        return this.optional(element) || /^(http)?(:\/\/)?(https)?(:\/\/)?(www)?(.)?[a-z0-9A-Z]+[a-z0-9A-Z_]+\.[a-z0-9A-Z]{2,5}/i.test(value);
    }, "Please provide a valid url.");
    
    jQuery.validator.addMethod("lettersonly", function(value, element) {
        return this.optional(element) || /^[a-z]+$/i.test(value);
    }, "Letters only please"); 
    
      jQuery.validator.addMethod("lettersandspace", function(value, element) {
        return this.optional(element) || /^[a-z\s]+$/i.test(value);
    }, "Only alphabetical characters and spaces are allowed."); 
    
    jQuery.validator.addMethod("alphanumeric", function(value, element) {
    return this.optional(element) || /^[a-zA-Z0-9-_]+$/i.test(value);
    }, "Letters, numbers, dash or underscores only please"); 
    
   //email validator (bcz the validator that jquery validate plugin provides validates ppgeu@gmail also)
    jQuery.validator.addMethod("myemail", function(value, element) {
    return this.optional(element) || /^[a-z][0-9a-z.]+(@)[0-9a-z]+[.][a-z]{2,3}$/i.test(value);
    }, "Invalid Email."); 
    
    jQuery.validator.addMethod("mydecimalnumber", function (value, element) {
    return this.optional(element) || /^(^[\d]+[.][0-9]{2}$)$/.test(value);
    }, "Please specify the correct number format. Ex(9999.99)");

    //adding custom methods ends here
	
	/* Purpose: Validating business register edit form
 	*/
    $("#contactform").validate({

           rules: {


                name: {
                    required: true,
                    lettersandspace:true, //validating by custom method
                    minlength:2,
                    maxlength:20
                },
                company: {
                    required: true,
                    lettersnumberspacedotandbracket:true, //validating by custom method
                    minlength:5,
                    maxlength:50
                },
                address:{
                    required: true,
                    minlength:5,
                    maxlength:200,
                    lettersnumberspacedotandbracket:true
                },
                city: {
                    required: true,
                    lettersonly:true,
                    minlength:2,
                    maxlength:20
                },
                state: {
                    required: true,
                    lettersonly:true,
                    minlength:2,
                    maxlength:20
                },
                zip:{
                    required: true,
                    digits:true,
                    maxlength:10
                },
                tel:{
                    required: true,
                    digits:true,
                    minlength:10,
                    maxlength:10
                },
                extension:{
                    required: true,
                    lettersnumberspacedotandbracket:true,
                    minlength:5,
                    maxlength:200
                },
                fax:{
                    required: true,
                    digits:true,
                    minlength:5,
                    maxlength:200
                },
                email:{
                    required:true,
                    myemail: true //validating by custom method
                }, 
                'currentcapitalavailable[]':{  //validating array field
                    required: true
                },
               balance3:{ //validating based on condition of other fields
                     required:function(element){
                        return ($('input:radio[name=balance1]:checked').val()=='2' &&               ($('#balance2').val()=='3' || $('#balance2').val()=='4'));
                     },
                     mydecimalnumber: true,
                     minlength:3,
                     maxlength:30
                }, 
                 schoolfee:{ //validating based on condition of other fields (one more example if schoolname is checked and schooladdress value is 1,2 or 3 then school fee must be filled)
                     required:function(element){
                        return ($('input:radio[name=schoolname]:checked').val()=='1' && ($('#schooladdress').val()=='2' || $('#schooladdress').val()=='3' || $('#schooladdress').val()=='4'));
                     }
                 },
                
            },

            // Specify the submit
            submitHandler: function() {
                $('.contactsubmit').prop('disabled',true); //disabling the submit button till page submits
                $('#popuploadercontact').show(); //show loader
                form.submit();  //submit form
            }
        });

}); // document.ready closed

That’s all you are done.

jQuery Validator also provide error placement feature which is optional but sometimes very useful when you don’t like default error placement.

Here is a small example of how to use this parameter for showing error messages for each field on your desired location in DOM.

        errorPlacement: function(error, element) {
              if (element.attr("name") == "address") {
                error.insertBefore(".address");
            } else if(element.is(":checkbox")){
                error.insertBefore(element.closest('p'));
                error.addClass('error_class');
            }  else if(element.is("select")){
                error.insertAfter(element.closest('div'));
                error.addClass('error_class');
            }  else {
                error.insertAfter(element);
                error.addClass('error_class');
            }
         }

You can place this param before submit handler and always keep in mind to place a comma after every param.