Reputation: 134
I currently have a function to validate a phone number. This info gets entered in a web app. It is later displayed in a windows app, and that's where the issue comes. I have a specific function that populates data to controls, but it only accepts one type of phone number format and that is
(123) 456-7890
This is the function we've been using, but it lets the user enter any format as long as it's 10 digits, so it can be something like 123-45-6789
function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');
if (fld.value == "") {
return false;
} else if (isNaN(parseInt(stripped))) {
return false;
} else if (!(stripped.length == 10)) {
return false;
}
return true;
}
I've looked through the web and usually they have a specific reg ex for 2 formats (123) 456-7890 | 123-456-7890
and the reg ex is (((\d{3}) ?)|(\d{3}-))?\d{3}-\d{4} however in my case I can only allow 1 format (with paranthesis)
Any way to change this so it can validate whether the phone number is in the exact format as I showed above? Thanks in advance
Upvotes: 0
Views: 1026
Reputation: 20269
Use the below RegExp to validate the phone number
const valid = "(123) 456-7890";
const invalid = "1234567890";
const re = /^\(\d{3}\) \d{3}-\d{4}$/;
console.log(
re.test(valid),
re.test(invalid)
);
Upvotes: 0
Reputation: 36584
You can try the following regex
let regex = /^\(\d{3}\) \d{3}-\d{4}$/
console.log(regex.test("(123) 456-7890")) // true
console.log(regex.test("123-456-7890")) //false
Upvotes: 2