user3395635
user3395635

Reputation: 17

phone number validation that accept only + and - signs

i have to write the Regular expression that accept two signs only + and - and can be of any no. of digit but + should be the first sign if it is there

Upvotes: 1

Views: 118

Answers (3)

Tanzeel Kazi
Tanzeel Kazi

Reputation: 3827

I am assuming the following:

  • + may only be at the beginning of the number
  • - should not be
    • at the beginning or end of the number
    • consecutively repeated

You could try this regular expression:

^\+?(?:[\d]+\-)*[\d]+$

Passes the following string examples:

  • +12-34-5678-90
  • 12-345-678-90
  • 1234567890

Fails the following string examples:

  • ++12-34-5678-90
  • 12+34-5678-90
  • 12-34-5678-90-
  • 12--34-5678-90

EDIT

As @Alovchin pointed out, the OP expressed the need to allow for dots (.) as well in the numbers in one of the answer comments. Although this requirement does not reflect in the question I am going to add it here just-in-case.

If the requirement is to allow for dots (.) as well then the above regex will need to be updated to the following.

^\+?(?:[\d]+[\-\.])*[\d]+$

Hope this helps.

Upvotes: 3

Alovchin
Alovchin

Reputation: 683

In C# try this one:

^\+?(?![\-\.])[\d\-\.]+(?<![\-\.])$

There's a better answer by Tanzeel Kazi.

Upvotes: 0

CodeGuru
CodeGuru

Reputation: 2803

Try this one

^\+?[0-9-]+$

Check here This is for indian numbers.

Upvotes: 3

Related Questions