Monday 29 September 2014

Useful Custom JQuery Validations using JQuery Validate

Here are some custom JQuery validate's method which can useful while working on various projects. Most of these are implemented by using Regular Expression according to my need. You can change expression whatever you required.

- Know more about JQuery Validate Plugin
- Know more about Regular Expression in Javascript

1. PAN Card: Find more details here
2. KEY: String should start with "__ and end with __". Ex: __Hello__
3. Landline: Landline Number (Ex. 0432-5435)
4. Amount: Ex. 50000.00
5. Interest Rate: Ex. 12.10, 5.2
6. Percentage: Ex. 100, 99.99, 1.2

$(document).ready(function() {

$.validator.addMethod("pan", function(value, element)
{
   return this.optional(element) || /^[A-Z]{5}\d{4}[A-Z]{1}$/.test(value);
}, "Invalid PAN Number");

$.validator.addMethod("key", function(value, element)
{
   return this.optional(element) || /^__[a-zA-Z]+__/.test(value);
}, "Invalid Key");

$.validator.addMethod('landline', function(value, element) {
    return this.optional(element) || /^\d{2,5}\-\d{3,9}$/.test(value);
}, 'Please specify a valid landline number');

$.validator.addMethod('amount', function(value, element) {
    return this.optional(element) || /^\d{1,9}[\.\d]+$/.test(value);
}, 'Please specify a valid Amount (Ex. 1000xxx)');

$.validator.addMethod('interest', function(value, element) {
    return this.optional(element) || /^\d{1,2}(\.\d{1,2})?$/.test(value);
}, 'Please specify a valid data');

$.validator.addMethod('percent', function(value, element) {
    return this.optional(element) || /^\d{1,2}\.\d{1,2}$/.test(value);
}, 'Please enter valid data (Ex. 25.00)');
});

Usage:

$("#myform").validate({
        rules: {
            "pan": {required: true},
            "amount": {amount: true}
            "landline": {landline: true},
            "interest_rate": {interest: true},
            "percent": {percent: true},
            "nospace": {required: true},
            "key": {noSpace: true}
        }
});

Thanks. Hope it'll help.