Search code examples
javascriptregexstringvalidationpcre

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

Solution

  • A really simple method you could use is:

    function isPhoneNumber(phone) {
        if (phone.match(/^(?:\+161)?\d{9}$/) {
            return true;
        } else {
            return false;
        }
    }