Yvon Huynh
Yvon Huynh

Reputation: 463

Regex for coercing input for phone number in javascript

I have an input for a phone number in french format The input accepts two kinds of format, so i can input this:

  1. 0699999999
  2. +33699999999

no check is done for the length of the number.

The table in database, the field is of varchar 12, i can have shorter input though. The constraints: input contains only digits from 0 to 9, optional '+' sign accepted only if it starts the string, not after.

Currently i am in Angular with a directive, in that directive the heart is this expression :

var transformedInput = inputValue.replace(/[^0-9]/g, ''); 

i want the optional leading '+' sign, how can i achieve this? thanks.

Upvotes: 1

Views: 178

Answers (2)

Sascha
Sascha

Reputation: 1218

You could make the plus sign optional:

if (/\+?\d*/.test(subject)) {
    // Successful match
} else {
    // Match attempt failed
}

subject is the text you want to check. \+ makes the plus sign a literal and the questionmark makes it optional.

If you just want to check wether ther is a plussign drop the questionmark. But if that is your goal don't use a regex. That is too much overhead. Simply get the first charactor of the trimmed string and check for the plus.

Upvotes: 2

potatopeelings
potatopeelings

Reputation: 41065

Change it to

var transformedInput = inputValue.replace(/[^0-9\+]/g, '').replace(/(.)\+/g, '$1'); 

Note - this will NOT add a + unless there is already a + in the input


What it does is

  1. Do not remove the + symbol on the first replace
  2. Remove every + symbol that is preceded by some character on the 2nd replace

Upvotes: 1

Related Questions