Monday, 3 October 2016

Jquery Validation For Masked Textbox

Jquery Validation cannot be used plainly for the masked textbox. To use Jquery validation for the masked textbox, we need to use Jquery validation addMethod to write custom method for adding validation for that masked textbox.

        
    $.validator.addMethod('numberForMasked', function(value, element, param){
        return !isNaN(value.replace(param, '').trim());
    }, "Ener only numbers");
    $.validator.addMethod("noDecimalForMasked", function(value, element, param) {
        return !(value.replace(param, '').trim() % 1);
    }, "No decimal numbers");
    $.validator.addMethod("minForMasked", function(value, element, param) {
        return value.replace(param[1], '').trim() >= param[0];
    }, "Number is too low");
    $.validator.addMethod("maxForMasked", function(value, element, param) {
        return value.replace(param[1], '').trim() <= param[0];
    }, "Number is too high");
    
Add rules for the masked text box in the form.

        
    var form = $("#form");
    form.validate({
        rules: {
            field: {
                required: true,
                numberForMasked: 'mask',
                noDecimalForMasked: 'mask',
                minForMasked: [1, 'mask'],
                maxForMasked: [999, 'mask']
            }
        },
        messages: {
            field: {
                required: "Please enter number",
                numberForMasked: "Please enter only numbers",
                noDecimalForMasked: "Please enter only integers",
                minForMasked: "Please enter atleast 1",
                maxForMasked: "Please enter less than 999"
            }
        }
    });
    
Here, mask is the text used for the masked text box, replace it with the text used in your masked textbox.

No comments:

Post a Comment