I am trying to apply a phone number masking including country code in below format.
1(999)99-9999
I am using this regex :
const re = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/
console.log(re.test(` 1(999)99-9999`))
but my validation fails.
CodePudding user response:
You can use
^\ ?\d \(\d{3}\)\d{2}[-\s\.]\d{4}$
JavaScript Example
function isValid(phone) {
return /^\ ?\d \(\d{3}\)\d{2}[-\s\.]\d{4}$/.test(phone);
}
console.log(isValid(" 1(999)99-9999"));
console.log(isValid(" 1(999)99 9999"));
console.log(isValid(" 1(999)99.9999"));