1

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.

2
  • regex only? it might be simpler to check for + before applying the regex and add it later again Commented Nov 26, 2015 at 7:44
  • i didn't write the directive and was looking for a similar solution, regex are powerful Commented Nov 28, 2015 at 22:01

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

thanks this worked for me, also to note: since i am using angular, white space is authorized in the input despite regex, unless you add ng-trim="false"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.