Search code examples
javascriptjqueryjquery-validatemaskedinput

jQuery: After Validation Error, my Input Mask function doesn't work on field


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.

I'm using jQuery, jQuery validate plugin, input mask from https://github.com/RobinHerbots/jquery.inputmask, and Bootstrap.

Here's a bit of my form that shows the birthdate field. My form has many other fields too.

 <form name="add_contact_quick" id="add_contact_quick" method="POST" class="horizontal-form">
        <div class="form-body">

        <div class="alert alert-danger display-hide">
          <button class="close" data-close="alert"></button>
                You have some form errors. Please check below.
        </div>
        <div class="alert alert-success display-hide">
            <button class="close" data-close="alert"></button>
                Your form validation is successful!
        </div>
    <div class="col-md-12">
      <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>

          <div class="modal-footer form-actions right">
                                <button type="button" class="btn default" data-dismiss="modal">Cancel</button>
                                <button type="submit" class="btn blue"><i class="fa fa-check"></i> Save</button>
                            </div
          </form>

Here's my javascript that will validate the form and show errors if validation fails.

<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>

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

Whatever value is entered into the birthdate input box is stripped of it's input mask, and I'm just left with numbers. When I try to edit the birthdate box again, no input mask is applied like it was on page load.


Solution

  • Thanks for commenting on this.

    It was driving me nuts.

    I took your suggestion and made a fiddle.

    jsfiddle.net/epyo7gn5/

    The interesting thing is that as I was making the fiddle, it WORKED!

    It made me realize that the inputmask plugin I was using was an older version. Using the updated plugin solved the whole issue.

    I feel a bit silly, but I learned a valuable lesson. I was unaware that the project used a "slightly" older version, but I never would have figured it out if it wasn't for this thread and suggestions.

    Thanks.