Conflict between jQuery Validate and Masked Input

后端 未结 7 646
梦谈多话
梦谈多话 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:03

    I tried some of the solutions but none worked for me, i'm using 'bootstrapValidator' (http://bootstrapvalidator.com/) and 'jquery.maskedinput' (http://digitalbush.com/projects/masked-input-plugin/) so if someone still have this problem, my solution was:

    My input was marked like this:

    
    

    And the full script like this:

    $(document).ready(function() {
       var telefone = $('#telefone'), //THAT'S MY INPUT WITH MASK
           form = telefone.parents("form"), //THAT'S MY FORM WITH THE VALIDATE
           alteredField = false; //THAT'S A FLAG TO SSE IF THE INPUT WAS ALTERED
    
                // APPLY MY MASK
                telefone.mask('(99) 9999-9999?9');
    
                // FOCUS ON ANY INPUT
                form.find('input[type=text]').focus(function(){
                    // REMOVE THE VALIDATION STATUS
                    $(form).data('bootstrapValidator').updateStatus($(this).attr('name'), 'NOT_VALIDATED');
                    // ENABLE THE SUBMIT BUTTON
                    $(form).data('bootstrapValidator').disableSubmitButtons(false);
                });
    
                // FOCUS ON THE MASKED INPUT
                telefone.focus(function(){
                    // DISABLE THE VALIDATE
                    $(form).data('bootstrapValidator').enableFieldValidators('telefone', false);
                    // ENABLE THE SUBMIT BUTTON
                    $(form).data('bootstrapValidator').disableSubmitButtons(false);
                }).blur(function(){ // BLUR ON THE MASKED INPUT
                    // GET THE INPUT VALUE
                    var value = telefone.val();
                    // ENABLE THE VALIDATE 
                    $(form).data('bootstrapValidator').enableFieldValidators('telefone', true);
                    // CHECK IF THE VALUE IS EMPTY
                    if(value != ""){
                        // CHANGE THE STATUS OF THE INPUT TO VALID 
                        $(form).data('bootstrapValidator').updateStatus('telefone', 'VALID')
                        // ACTIVE THE FLAG
                        alteredField = true;
                    }else if (alteredField) { // IF THE INPUT WAS ALTERED BEFORE AND DON'T HAVE VALUE
                        // CHANGE THE STATUS OF THE INPUT TO INVALID
                        $(form).data('bootstrapValidator').updateStatus('telefone', 'INVALID')
                    };
                });
    
            });
    

    This code modifies the standard behavior of the 'bootstrapValidator', but was the only way that I gotta to solve the bug.

    I don't know about performance issues, so please modify and improve the code ^^ Hope that this help ^_^

提交回复
热议问题