Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

javascript - validate phone number length between 5-15

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;
    }
question from:https://stackoverflow.com/questions/65932498/validate-phone-number-length-between-5-15

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...