C# 如何验证电话号码字段以仅接受数字和最多 12 位数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18273154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:45:55  来源:igfitidea点击:

How to Validate Phone Number Field to accept only numbers and maximum 12 digits?

c#asp.net.netregex

提问by Yasmeen Ansari

I am doing validation for 10 digit Indian phone numbers (coding below). I am accepting digits only. What I can't seem to figure out is how to throw an error so that if the number entered begins with text or special characters and also not allow more than 12 Digits. Or either trunacte numbers to 12 digits if user enters more than 12 digits.

我正在验证 10 位印度电话号码(编码如下)。我只接受数字。我似乎无法弄清楚如何抛出错误,以便输入的数字以文本或特殊字符开头,并且也不允许超过 12 位数字。或者,如果用户输入超过 12 位数字,则将数字截断为 12 位数字。

<asp:RegularExpressionValidator ID="phoneregularExpression" runat="server" ErrorMessage="MoreThan10" EnableClientScript="false"
ControlToValidate="txtphone" Display="Static" Text="Please enter atleast 10 digits" ValidationExpression="^([0-9\(\)\/\+ \-]*)$"></asp:RegularExpressionValidator>

Thanks In Advance.

提前致谢。

采纳答案by Ahmed Alaa El-Din

Use this i set max length to 12 to TextBox and Validator and validated it on regularexpression and tried it

使用这个我将最大长度设置为 12 到 TextBox 和 Validator 并在正则表达式上验证它并尝试它

<asp:TextBox runat="server" ID="txt" MaxLength="12"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
        ErrorMessage="Error" ForeColor="Red" ControlToValidate="txt"
        ValidationExpression="^[0-9]{12}$"></asp:RegularExpressionValidator>

回答by Microsoft DN

Try this regular expression

试试这个正则表达式

^[0-9]{12}$

回答by Mike Perrenoud

This Regex will make sure there is 10, but allow not more than 12:

此正则表达式将确保有 10 个,但不允许超过 12 个:

^([0-9]{10,12})$

Here is a Regex 101to prove it.

这是一个正则表达式 101来证明它。

This one will allow 10 or 12 only, and an 11 digit one will fail.

这一个将允许10或12和11位一个将失败。

^([0-9]{10}|[0-9]{12})$

Here is a Regex 101to prove it.

这是一个正则表达式 101来证明它。

This one will allow 1 to 12 digits:

这将允许 1 到 12 位数字:

^([0-9]{1,12})$

Now, you've set EnableClientScriptto false here. Which means there won't be any JavaScript validating it client-side. However, you need to make sure you call this.Validate()to force validation on the page beforeattempting to check if the validator IsValid.

现在,您已EnableClientScript在此处设置为 false。这意味着不会有任何 JavaScript 在客户端验证它。但是,你需要确保你打电话this.Validate()来强制页面上验证之前尝试检查验证IsValid

回答by sangram parmar

Try this

尝试这个

1)maximum limit = 12

1)最大限制= 12

ValidationExpression="\d{0,12}"

2)require length = 12 but not limit

2)要求长度= 12但不限制

ValidationExpression="\d{12}"