JQuery masked input plugin conflicts with validation plugin

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

If you put focus in a text field that is masked, leave it without entering any information (or do not enter enough information to satisfy the mask), the masked input plugin will delete everything, leaving you with an empty text field.

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

The validation plugin fires its blur event to a masked input plugin. This leads to checking the passage of the text field (since it has text), then the connected input plugin masks and deletes the text. The field must be marked as invalid once it has lost focus.

I tried using the regex checker. It is approaching, but again, since it starts before the masked input plugin clears the field, it shows an error when it should not (although the error disappears when the user tries to submit the form).

I also tried this:

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

This works, but also interferes with the initial behavior of the validator: the fields are not checked until the submit button is pressed, after which they are checked when they lose focus.

I installed jsFiddle , which depicts the problems I encountered.

+6
source share
3 answers

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

Cooleos, so if I got it right, the hidden plugin would remove the input, hence the chaos. :)

In the demonstration of the example above, the entered number will remain entered, and you can connect it with.

Oh, and if that helps, be sure to accept the answer and vote.

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

You probably just need to make the entire mask an option 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'); });​ 
+7
source

You can repeat the input check when focusing / blurring.

 $('#inputId').on('blur', function(){ $('#formId').validate().element('#inputId') }); 
+2
source
 phone_no:{ icon: 'false', validators: { notEmpty: { message: 'Contact Phoneno is required' }, regexp: { regexp: /^\d{3}\-\d{3}\-\d{4}$/, message: 'Please Enter Valid Phone number' } } } 

Type this on formvalidator and perfect

+1
source

Source: https://habr.com/ru/post/914425/


All Articles