简体   繁体   中英

Regex of phone number - how to make sure the user won't put +-*+-*+-*+-*?

I want to allow the user to enter only patterns like:

+9720545455454

056565656345

03-43434344

0546-4234234

*9090

+97203-0656534

Meaning, I don't want to allow the user to gibberish everything together, like:

+954-4343+3232*4343+-

+-4343-+5454+9323+234

How can I fixed this pattern

public static bool IsPhoneNumberCorrect(string phoneNumber)
{
    return Regex.IsMatch(phoneNumber, @"^[0-9*+-]+$");
}

for that purpose?

If you do not care about digit group length, you can allow + or * only at the beginning, and then match initial digits and then optional groups of hyphen+digits:

return Regex.IsMatch(phoneNumber, @"^[+*]?\d+(?:-\d+)*$");

See demo

Note you can limit the number of hyphen+digit with a quantifier. Say, there can be none or 1:

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

See another demo

And in case there can be more than 1, use a limiting quantifier:

^[+*]?\d+(?:-\d+){0,3}$"
                 ^^^^^

Here, {0,3} means 0, 1, 2 or 3 repetitions of the hyphen+digits group.

^(?!(.*\+){2})(?!(.*-){2})(?!(.*\*){2})[0-9*+-]+$

YOu can use lookaheads to make sure special characters appear only once .See demo.

https://regex101.com/r/vV1wW6/1

What you first need to do is identify what exactly the pattern is. This doesn't need to be in code. In you example, I see a leading character, followed by a first number group, followed by an optional dash and second number group. The leading character can be +, * or 0. The number groups are one digit between 1 and 9 followed by one or more digits 0 to 9. Translating each element gives:

Leader: [+*0]

Dash: -

Number group: [1-9][0-9]+

Throwing everything together you get

[\+\*0][1-9][0-9]+(-[1-9][0-9]+)?

Some groups may have minimum and maximum lengths, you can still work that in changing + to {min, max}.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM