# Other Languages > jQuery >  [RESOLVED] After Validation Error, my Input Mask function doesn't work on field

## chris.cavage

I am using JQuery to successfully validate my form.

I added an masked input to my birth date field in my form.  The masked input plugin is from: https://github.com/RobinHerbots/jquery.inputmask

On load, the birthdate field has the masked input working properly.  If the form is submitted and validation is failed on that field of other fields in the form: the birthdate field is stripped of it's masked character separators and the masked input is not working anymore.



```
<div class="col-md-4">
  <div class="form-group">
    <label class="control-label">Date of Birth</label>
     <div class="input-icon right">
       <i class="fa"></i>
       <input id="birthdate" name="birthdate" type="text" class="form-control">
     </div>
  </div>
</div>
```

My script:



```
<script>
$(document).ready(function() {
          
        var form = $('#add_contact_quick');
        var error = $('.alert-danger', form);
        var success = $('.alert-success', form);

         $('#add_contact_quick').validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-block help-block-error', // default input error message class
                focusInvalid: true, // do not focus the last invalid input
                ignore: "",  // validate all fields including form hidden input
                rules: {
                    friends_call_me: {
                        required: true
                    },
                    first: {
                        required: true
                    },
                    last: {
                        required: true
                    },
                    email: {
                        email: true
                    },
                    birthdate: {
                        date: true 
                    },
                },

                invalidHandler: function (event, validator) { //display error alert on form submit              
                           success.hide();
                           error.show();
                           Metronic.scrollTo(error, -200);             
                },

                errorPlacement: function (error, element) { // render error placement for each input type
                            var icon = $(element).parent('.input-icon').children('i');
                            icon.removeClass('fa-check').addClass("fa-warning");  
                            icon.attr("data-original-title", error.text()).tooltip({'container': 'body'});
                },


                highlight: function (element) { // hightlight error inputs
                            $(element)
                                .closest('.form-group').removeClass("has-success").addClass('has-error'); // set error class to the control group   
                },

                unhighlight: function (element) { // revert the change done by highlight

                },

                success: function (label, element) {
                    var icon = $(element).parent('.input-icon').children('i');
                    $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                    icon.removeClass("fa-warning").addClass("fa-check");
                },

                submitHandler: function(form) {
                    //form[0].reset();
                    success.show();
                    error.hide();
                    Metronic.scrollTo(success, -200);
                    $.ajax({
                        url: "ajax_insert.php?table=contacts",
                        type: form.method,
                        data: $(form).serialize(),
                        success: function(response) {
                                //response here if data response
                            if (response.redirect) {
                                // data.redirect contains the string URL to redirect to
                                    window.location.href = reponse.redirect;
                                    }
                        }        
                    });
                    
                }

         }); 
   $("#birthdate").inputmask("99/99/9999");
});
 
</script>
```


Any thoughts why the input mask stops working after a failed validation?  Thanks.

----------


## szlamany

Can you set a break at this line of code

$("#birthdate").inputmask("99/99/9999");

using something like FireBug?

Also - why are you submitting the whole form to validate a birthdate?

----------


## chris.cavage

I added a breakpoint to that line.

It stops when the page first loads to apply the mask to the birthdate input.   That's all.




> Also - why are you submitting the whole form to validate a birthdate?


Not sure?  I have a form with many input fields.  I just showed my birthdate field as that's the one I'm having issues with the input mask.

I thought what was happening was when the form was submitted, jquery recognizes submit was clicked and then runs it's validation (.validate plugin).  If something isn't submitted properly, then my error message is displayed and the appropriate text boxes turn red.  I am also using Bootstrap for my css.

Do I have something set up wrong?  I'd be happy to change it to make it better.

Adding the input mask to the birthdate works only when the date is entered initially.  But if a validation error occurs for another field, then the input mask isn't applied to the birthdate field any more!  

Thanks!

----------


## szlamany

You say the second time the breakpoint is not hit.

What if you set a breakpoint at the top of the READY event?  Does it break the second time?  If so then step through and see where it veers off.

With my web apps I use a lot of AJAX.  Basically I never re-submit the page.

----------


## chris.cavage

If I set that breakpoint at the READY event, no it only breaks when the page first loads.  

I was trying to research others having the same problem before - it was hard to research.

I am wondering if there is a way with jQuery to attach the input mask to the input field permanently instead of having it apply the input mask on page load.  OR maybe there's a way to re-apply the input mask if the validation doesn't pass and my error message is shown.

Not sure how to do that! But, maybe that would do the trick?

----------


## szlamany

If the READY event is not firing the second time then you are using AJAX also, I would guess.

Please show me the JAVASCRIPT code that runs when the data is submitted.

----------


## chris.cavage

Ajax is called from jQuery if the form validates properly.  The ajax URL to process the data is:  ajax_insert.php?table=contacts



```
<?php
require_once 'core/init.php';

$user = new User();
if(!$user->isLoggedIn()) {
	Redirect::to('login.php');
}

$contact = new Contact();

       DB::getInstance()->insert($_GET['table'], $_POST);
        $data = array("redirect" => "index.php");

$json= json_encode($data);
echo $json;

?>
```

----------


## szlamany

Sorry - didn't see that.

Put a break at the IF statement here - does it break at that location?

*if (response.redirect) {*



```
                        success: function(response) {
                                //response here if data response
                            if (response.redirect) {
                                // data.redirect contains the string URL to redirect to
                                    window.location.href = reponse.redirect;
                                    }
                        }
```

----------


## chris.cavage

Yeah it breaks there, but only if the validation passes.

If I put a break at error.show in:



```
 invalidHandler: function (event, validator) { //display error alert on form submit              
                           success.hide();
                           error.show();
                           Metronic.scrollTo(error, -200);
                },
```

... that is where the break happens when the form's validation fails.  I need it to run my:   $("#birthdate").inputmask("99/99/9999"); AGAIN at this point, I'm guessing to make the input mask work again.   But if I simply do this:



```
 invalidHandler: function (event, validator) { //display error alert on form submit              
                           success.hide();
                           error.show();
                           Metronic.scrollTo(error, -200);
                          $("#birthdate").inputmask("99/99/9999");
                },
```

... and when I put a break on: $("#birthdate").inputmask("99/99/9999"); in the above, it does break at that point if the form doesn't pass validation, but the input mask is not showing in the input field.

----------


## szlamany

There is where I was heading - to find what code was running in the invalid data condition...

Where you put that line of code - break at that spot - and at an immediate prompt

What does this return?

* $("#birthdate").length*

----------


## chris.cavage

I'm hoping what I did here is what you are looking for:



```
 invalidHandler: function (event, validator) { //display error alert on form submit              
                           success.hide();
                           error.show();
                           Metronic.scrollTo(error, -200);
                           $("#birthdate").inputmask("99/99/9999");
                            alert($("#birthdate").length);
                },
```

So, if the form isn't validated properly, I get a message box that ALWAYS has value of '1'.  No matter what is in the birthdate input.

I am researching this and found someone who made this fiddle that it IS working:

http://jsfiddle.net/2hdTn/

However, I don't quite understand how the .addmethod works with the jquery validation plugin.  I am also wondering if there's a way to adapt that to work with my birthdate input mask, which is different from the phone number mask they are using in that fiddle.

----------


## szlamany

1 is the correct value - the $("#birthdate") object is an ARRAY of items that match that selector.

I wanted to see "1" so I would know for sure that DOM element is found.

And it is.

I use AJAX with POST's and not GET's so I don't get a whole form back line you do with this:

window.location.href = reponse.redirect

which means the DOM is only changed by my direct changes to it in JAVASCRIPT.

----------


## chris.cavage

Oh, I see.  This is my first stab at ajax,but this jQuery input mask is driving me nuts.

I need a way to keep that mask in the input box if the validation fails, right?  I am confused as to why the input mask is cleared completely from the input box just because the validation fails!  

Makes no sense to me!

----------


## chris.cavage

So, this drove me nuts, but I decided to scrap that particular input mask plugin and I tried this one:

https://github.com/igorescobar/jQuery-Mask-Plugin

I use it like this on document ready:  

 $("#birthdate").mask("99/99/9999", {placeholder: "__/__/____"});

That's it. If the form doesn't pass validation, the mask doesn't disappear!  Maybe there's an issue with the other plugin? 

Either way, I have a solution.

----------


## szlamany

I'm in need of a phone # mask - will this mask you used here do that as well??

----------


## chris.cavage

Yeah, I'm using it now for all my phone numbers (with optional extensions) like this:

 $(".phone-mask").mask("(999) 999-9999 x99999");

Working great so far.

----------


## chris.cavage

Well, I feel like a silly man.

I can finally put this to bed now.  

It turns out (unbeknownst to me) that my project folder that contained all my assets (which included the input mask plugin) was using an older input mask plugin from: https://github.com/RobinHerbots/jquery.inputmask

After updating everything to the newest plugin, the problem went right away! 

Sheesh. Lesson learned.

I like this input mask plugin better, so I'll be switching back to it.

Thanks again for the help.

----------

