Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Length validation of masked Input field

I have the following masked field:

<input id="phone1" placeholder="(___) ___-____"/>

masking is done like this:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
        <script>
        $("#phone1").inputmask({ "mask": "(999) 999-9999" });
        </script>

I want to do the length validation of the phone field. The phone field should be exactly 10 characters long or with masked input, it should be 14 characters long.
I don’t want to do the validation on submit button, but I want to do the length validation of phone field "onfocusout" or when someone tabs out of the field. I just want to display a message underneath the phone field saying "this field should be 10 characters long" if someone puts less than 10 character. This masking is not letting the user put more than 10 character. This phone field is not a required field.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

any help will be highly appreciated.

>Solution :

Just define validation on .keyup event, so if there is any validation error, it will display when the user is typing. Use .replace(/\D/g,'') to remove the non-numerical string.

$("#phone1").inputmask({ "mask": "(999) 999-9999" }).keyup((e) => {
  if(e.target) {
    let value = e.target.value.replace(/\D/g,'');
    if (value.length != 10) {
      $('#error').html('this field should be 10 characters long');
    } else {
      $('#error').html('');
    }
  }
});
#error {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>

<input id="phone1" placeholder="(___) ___-____"/>
<div id="error"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading