开发者

How to validate a phone number OR allow blanks with RegEx in a text field?

I'm trying to validate a phone number against a RegEx.

I was provided with this answer:

Regular Expression for Phone Number

which defines the expression to validate the following phone number: +44 (0) 1234 123456

I've ported it from JS to C#, to be

var regexPhone = new Regex(@"^(?!([^-]*-){5})(\+\d+)?\s*(\(\d+\))?[- \d]+$");

This works, but the validator is also applied to phone number fields that are allowed to be blank, e.g. a Fax (not everyone has one of those old-fangled devices anymore).

How can I change this to allow blanks, as well as to validate against the number above?

edit: the answer below works for th开发者_Python百科e number above but it's failing for this: + 44 (0)20 1234 1234. Is there something else I can add for this?


Simply add a |^$ at the end:

var regexPhone = new Regex(@"^(?!([^-]*-){5})(\+\d+)?\s*(\(\d+\))?[- \d]+$|^$");

edit: Since you want a more relaxed regex, whitespace-wise, just sprinkle in \s*:

var regexPhone = new Regex(@"^\s*(?!([^-]*-){5})(\+\s*\d+)?\s*(\(\s*\d+\s*\))?\s*[- \d]+\s*$|^\s*$");


I've tried it and it works.

 <asp:TextBox runat="server" ID="testInput"></asp:TextBox>
            <asp:RegularExpressionValidator ValidationExpression="aa|^$" 
runat="server" ControlToValidate="testInput"></asp:RegularExpressionValidator>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜