简体   繁体   中英

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;
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM