Search code examples
javascriptregexecmascript-2016

Regular-Expression Phone number validation with spaces and characters with minimun digits


I have less skill for the Regex and I have a quick question. I need to validate phone number input with regEx.

Explanation/expression will be really appreciated. The Phone numbers can be any of the following formats:

(94) 123 345
(94).456.7899
(94)-456-7899
94-456-7899
+94 456 7899
94 456 7899
0094 456 7899
(94) 123
122 3454
1223454

1) Number can include spaces and characters or without characters.
2) It should have minimum 5 digits without spaces and characters. (I stuck at this point)

1st try

export const basicPhoneNumber = value =>
value && !/^\+?\d+$/i.test(value) 
? 'Invalid phone number' 
: undefined;

2nd try

  export const basicPhoneNumber = value =>
  value && !/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4,})/i.test(value) 
  ? 'Invalid phone number' 
  : undefined;

Thanks a lot for all your help and have a good one!


Solution

  • Phone number validation with regular expression is rather complicated, especially in such cases, yet we can try with an expression similar to:

    ^\+?\(?([0-9]{2,4})[)\s.-]+([0-9]{3,4})([\s.-]+([0-9]{3,4}))?$
    

    which would likely fail with some desired instances that are not listed, regardless that some inputs such as (000) 000-0000 are not really phone numbers.

    const regex = /^\+?\(?([0-9]{2,4})[)\s.-]+([0-9]{3,4})([\s.-]+([0-9]{3,4}))?$/gmi;
    const str = `(94) 123 345
    (94).456.7899
    (94)-456-7899
    94-456-7899
    +94 456 7899
    94 456 7899
    0094 456 7899
    (94) 123
    122 3454`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    Demo 1

    Edit

    For allowing 12234554, we would make an optional group for ([)\s.-]+)?,

    ^\+?\(?([0-9]{2,4})([)\s.-]+)?([0-9]{3,4})([\s.-]+([0-9]{3,4}))?$
    

    Demo 2