Reputation: 4945
I have this really cool validation script for entering currency which I love
$("#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.
$("#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
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
Reputation: 758
A better way is to use
jquery input masks
.Also you can customize theinput mask
..
Follow the links
Upvotes: 3