Conflict between jQuery Validate and Masked Input

后端 未结 7 678
梦谈多话
梦谈多话 2020-12-08 10:40

I\'ve got a form that\'s using both jQuery Validate and Masked Input for phone number and US zip code fields.

For example, for a US zip code, Masked Input allows only

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 11:02

    I tried following solution, and it works like a charm.

    $("[data-input-type=phone]", "body")
      .mask("(999) 999 99 99")
      .bind("blur", function () {
        // force revalidate on blur.
    
        var frm = $(this).parents("form");
        // if form has a validator
        if ($.data( frm[0], 'validator' )) {
          var validator = $(this).parents("form").validate();
          validator.settings.onfocusout.apply(validator, [this]);
        }
      });
    

    What triggers the problem is event ordering. When an element is masked, it is validated by maskedinput plugin on blur, but same element is validated by validator plugin on focusout event (which is a wrapper for blur on non-ie browsers) which is called before maskedinput's blur.

    In this situation input element has the value "(___) ___ __ __" when validator checks for the value. When code reaches maskedinput's blur event, plugin tests and clears the value since it is not a valid input.

    Validation result may be different for each validation case. For instance required rules will pass with success since element has a value. non-required number fields will fail even if we leave the input empty since a mask like "999" may be tested as 12_

    the code above tests if form of masked input has validation attached to it, and recalls focusout event handler. Since our handler is attached as the latest, hopefully it will be called at last.

    A warning, code simply copies behavior of validation plugin. It will probably work for a decade but may fail if validation plugin decides to do things different than now.

    sincerely

提交回复
热议问题