Reputation: 745
I want to validated phone number in react native. Phone number minimum length should be 5 and maximum 15. I created a function for that but it's showing error when number is above 5. Can someone tell me how to validate it properly?
if (!/(^\d{15}$)|(^\d{5}-\d{4}$)/.test(phoneNumber)) {
return strings.PLEASE_ENTER_PHONE_NUMBER_VALID;
}
Upvotes: 0
Views: 1645
Reputation: 177830
12345-1234 and 1234512345112345 both work as expected
https://regex101.com/r/bDFFE9/1
Do you mean 5 to 15 digits are ok? Then you need
/(^\d{5,15}$)|(^\d{5}-\d{4}$)/
https://regex101.com/r/bDFFE9/3/
Like
const testPhone = phoneNumber => {
if (!/(^\d{5,15}$)|(^\d{5}-\d{4}$)/.test(phoneNumber)) {
return "PLEASE_ENTER_PHONE_NUMBER_VALID";
}
return "ok"
};
// ok:
console.log(testPhone("12345"))
console.log(testPhone("12345-1234"))
console.log(testPhone("1234512345"))
console.log(testPhone("123451234512345"))
//nok
console.log(testPhone("1234"))
console.log(testPhone("12345--1234"))
console.log(testPhone("12345123451234512345"))
Upvotes: 4