Cesar Bielich
Cesar Bielich

Reputation: 4945

Phone number validation with jQuery

I have this really cool validation script for entering currency which I love

Demo Currency Validator

$("#saleprice").on("keyup", function(){
    var valid = /^\d{0,4}(\.\d{0,2})?$/.test(this.value),
        val = this.value;

    if(!valid){
        console.log("Invalid input!");
        this.value = val.substring(0, val.length - 1);
    }
});

But I would love to have the same thing to validate a phone number. Here is my fiddle with the regex for a phone, but I cant seem to get it to work. The code is not allowing any characters to be typed in even though I specify characters like () as well as numbers and -,. to be allowed in the regex.

Demo Telephone Validator

$("#telephone").on("keyup", function(){
    var valid = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/.test(this.value),
        val = this.value;

    if(!valid){
        console.log("Invalid input!");
        this.value = val.substring(0, val.length - 1);
    }
});

I would like to allow the following formats of a phone number.

Upvotes: 2

Views: 12502

Answers (2)

guest271314
guest271314

Reputation: 1

Try setting input element maxlength to 10 ; replace non-digit characters ; format value when input length is ten characters

$("input").on("keyup", function(e) {
  e.target.value = e.target.value.replace(/[^\d]/, "");
  if (e.target.value.length === 10) {
    // do stuff
    var ph = e.target.value.split("");
    ph.splice(3, 0, "-"); ph.splice(7, 0, "-");
    $("label").html(ph.join(""))
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" maxlength="10" placeholder="tel: input ten numbers" />
<label for="input"></label>

Upvotes: 2

Nithin Krishnan P
Nithin Krishnan P

Reputation: 758

A better way is to use jquery input masks.Also you can customize the input mask..

Follow the links

1.masking 1

2.masking 2

Upvotes: 3

Related Questions