Search code examples
javascripthtmllivevalidation

How to check if masked input field is empty


I am using this masked input plugin and I would like to check when the field is empty. Below is what I have tried but it does not seem to work:

HTML

<input type="text" name="phone" id="phoneid" />

Le JavaScript:

$("#phoneid").mask("999-999-9999");

This code does not work

            $("#phoneid").keyup(function(){
                if($("#phoneid").val().length == 0){
                    alert(111);
                }
            });

Solution

  • The masking plugin that you're using alters the value of the input element.

    When the element is empty, it has a value of ___-___-____.

    You could simply strip out the _/- characters when checking the length of the value:

    $("#phoneid").on('keyup', function() {
      if (this.value.replace(/[_-]/g, '').length === 0) {
        alert('Empty');
      }
    });
    

    Alternatively, you could also check if the value only contains the _/- characters:

    $("#phoneid").on('keyup', function() {
      if (/^[_-]+$/.test(this.value)) {
        alert('Empty');
      }
    });