Saturday, October 20, 2018

The simpliest jQuery form validation

Let's start with the following simple example









To achieve this we need to use the following scripts and css





Create a simple form

And finally the javascript code. The 'validate' method contains the set of rules and messages. Messages are used for change default error messages.

To create custom validation rule we can add the following code:
jQuery.validator.addMethod('customValidation1', customFunction1);
jQuery.validator.addMethod('customValidation2', customFunction2);
jQuery.validator.addMethod('genderValidation', function(value, element, arg){
   return value != arg;
});

function customFunction1(){
   //Some logic
   return true;
}

function customFunction2(){
   //Some logic
   return false;
}

And now use 'customValidation1' and 'customValidation2' as rules
$( "#myform1" ).validate({
  rules: {
    field1: {
      customValidation1: true
    },
    field2: {
      customValidation2: true
    },
    gender:{
      genderValidation: 'Animal'
    }
  },
  messages: {
    field1: {
      customValidation1: 'Custom validation 1 failed'
    },
    field2: {
      customValidation2: 'Custom validation 2 failed'
    },
    gender: {
      genderValidation: 'Hey, you cannot be an animal!'
    }
  }
});

It should look like this:





To get more information ref this link
https://jqueryvalidation.org/

No comments:

Post a Comment