Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery masked input plugin conflicts with validation plugin

Given a text box that is masked using the Masked Input plugin, and is marked as a required field by the Validation Plugin, consider the following:

If you put your focus in a text box that is masked, then leave it without entering any information (or don't input enough information to satisfy the mask), the masked input plugin will delete everything, leaving you with an empty text box.

$("#phoneNumber").mask("(999) 999-9999? x999999");
$("#sampleForm").validate({
    rules: {
        phoneNumber: "required"
    }
});

The validation plugin seems to be firing its blur event before the masked input plugin. This results in the text box passing validation (as it does have text in it), then the masked input plugin kicks in and removes the text. The field should be marked as invalid as soon as it has lost focus.

I've tried using a regular expression validator. It gets close, but again, because it triggers before the masked input plugin has cleaned up the field it shows an error when it should not (though the error goes away when the user tries to submit the form).

I've also tried this:

$('input').bind('unmasked.maskedInput', function () { $(this).valid(); });

This works, but it also interferes with the validator's initial behavior: fields are not validated until the submit button is pressed, then they are validated when they lose focus.

I've setup a jsFiddle that depicts the issues I'm running into.

like image 353
Mike Avatar asked Apr 28 '12 18:04

Mike


1 Answers

Hiya working demo http://jsfiddle.net/2hdTn/

Cooleos so if I got it right masked plugin was removing the input hence the chaos. :)

In the sample demo above the entered number will remain entered and you can hook up the validation with it.

Oh and if this helps don't forget to accept the the answer and up vote.

Also see here: there is also clearEmpty: false http://view.jqueryui.com/mask/tests/visual/mask/mask.html

You probably just need to make the whole mask optional and bingo it will work :)

(Please let me know if I missed anything)

Jquery COde

jQuery.validator.addMethod("usPhoneFormat", function (value, element) {
    return this.optional(element) || /^\(\d{3}\) \d{3}\-\d{4}( x\d{1,6})?$/.test(value);
}, "Enter a valid phone number.");

$.fn.ready(function () {

    $("#sampleForm").validate({
        rules: {
            phoneNumber: "required",
            phoneNumberRegEx: {
                usPhoneFormat: true,
                required: true
            },
            phoneNumberReg: "required"
        },
        submitHandler: function (form) {
            alert("submitted.");
        }
    });
    $(".phone").mask("?(999) 999-9999 x999999");
    //alert('foo');
});

​
like image 100
Tats_innit Avatar answered Sep 21 '22 22:09

Tats_innit