Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write regex pattern from my function for validation custom phone numbers?

I have my own function to check phone number:

function isPhoneNumber(phone) {
    var regexForPhoneWithCountryCode = /^[0-9+]*$/;
    var regexForPhoneWithOutCountryCode = /^[0-9]*$/;
    var tajikPhone = phone.substring(0,4);
    if(tajikPhone == "+161" && phone.length !== 13) {
        return false;
    } 
    if(phone.length == 9 && phone.match(regexForPhoneWithOutCountryCode)) {
        return true;
    } else if(phone.length > 12 && phone.length < 16 && phone.match(regexForPhoneWithCountryCode)) {
        return true;
    } else return false;
}

My function also work, but not completely correct.

Rules for validate phone number:

  • Max length: 13
  • Min length: 9

When max length == 13:

  • Contain only: 0-9+
  • First charackter match: +
  • 3 charackters after "+" must be: 161

When max length == 9:

  • Contain only: 0-9

Example valid numbers:

  • +161674773312
  • 674773312
like image 627
Andreas Hunter Avatar asked Jan 01 '26 22:01

Andreas Hunter


1 Answers

A really simple method you could use is:

function isPhoneNumber(phone) {
    if (phone.match(/^(?:\+161)?\d{9}$/) {
        return true;
    } else {
        return false;
    }
}
like image 86
Jack Bashford Avatar answered Jan 03 '26 10:01

Jack Bashford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!