33

我正在尝试使用正则表达式来验证电话号码并在提交无效号码或电话号码时返回错误。

MVC 代码

<ol class="row">
    <li class="cell" style="width: 20%;">Phone Number:</li>
    <li class="cell last" style="width: 60%;">
        @Html.TextBoxFor(model => model.PhoneNumber, new { @class = "textbox" }) 
        @Html.ValidationMessageFor(model => model.PhoneNumber)
    </li>
</ol>

C#代码

[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
[Required(ErrorMessage = "Phone Number Required!")]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
                   ErrorMessage = "Entered phone format is not valid.")]
public string PhoneNumber { get; set; }

但是,输入框不会向用户显示一条消息,表明提交的电话号码无效。

4

9 回答 9

77

模型

[Required(ErrorMessage = "You must provide a phone number")]
[Display(Name = "Home Phone")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string PhoneNumber { get; set; }

看法:

@Html.LabelFor(model => model.PhoneNumber)
@Html.EditorFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)
于 2015-03-06T18:17:43.113 回答
8

尝试使用 Mobile No 的简单正则表达式

[Required (ErrorMessage="Required")]
[RegularExpression(@"^(\d{10})$", ErrorMessage = "Wrong mobile")]
public string Mobile { get; set; }
于 2016-06-15T08:18:09.850 回答
6

您在页面上没有验证器。添加类似这样的内容以显示验证消息。

@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
于 2015-03-06T18:13:37.203 回答
4

除了上面的答案,试试这个最小和最大长度:

在模型中

[StringLength(13, MinimumLength=10)]
public string MobileNo { get; set; }

在视图中

 <div class="col-md-8">
           @Html.TextBoxFor(m => m.MobileNo, new { @class = "form-control" , type="phone"})
           @Html.ValidationMessageFor(m => m.MobileNo,"Invalid Number")
           @Html.CheckBoxFor(m => m.IsAgreeTerms, new {@checked="checked",style="display:none" })
  </div>
于 2015-12-31T11:28:05.463 回答
4

要以(###) ###-####格式显示电话号码,您可以创建一个新的 HtmlHelper。

用法

@Html.DisplayForPhone(item.Phone)

HtmlHelper 扩展

public static class HtmlHelperExtensions
{
    public static HtmlString DisplayForPhone(this HtmlHelper helper, string phone)
    {
        if (phone == null)
        {
            return new HtmlString(string.Empty);
        }
        string formatted = phone;
        if (phone.Length == 10)
        {
            formatted = $"({phone.Substring(0,3)}) {phone.Substring(3,3)}-{phone.Substring(6,4)}";
        }
        else if (phone.Length == 7)
        {
            formatted = $"{phone.Substring(0,3)}-{phone.Substring(3,4)}";
        }
        string s = $"<a href='tel:{phone}'>{formatted}</a>";
        return new HtmlString(s);
    }
}
于 2016-03-22T20:08:30.453 回答
1

尝试这个:

[DataType(DataType.PhoneNumber, ErrorMessage = "Provided phone number not valid")]
于 2016-06-15T08:52:09.317 回答
1

或者您可以使用 JQuery - 只需将您的输入字段添加到“电话”类并将其放入您的脚本部分:

$(".phone").keyup(function () {
        $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));

没有错误消息,但您可以看到电话号码的格式不正确,直到您输入所有十位数字。

于 2016-07-01T20:42:29.643 回答
1

[DataType(DataType.PhoneNumber)]没有任何开箱即用的验证逻辑。

根据文档

DataTypeAttribute属性应用于数据字段时,您必须执行以下操作:

  • 根据需要发出验证错误。

[Phone]属性继承自[DataType].NET Framework 4.5+ 并在其中引入,并且位于 .NET Core 中,它确实提供了自己的验证逻辑风格。所以你可以这样使用:

[Phone()]
public string PhoneNumber { get; set; }

但是,电话号码的开箱即用验证非常宽松,因此您可能会发现自己想要从 DataType 继承并实现自己的IsValid方法,或者正如其他人在这里建议的那样,使用正则表达式&RegexValidator来约束输入。

注意:使用正则表达式时要小心,不要按照最佳实践进行不受约束的输入,因为 .NET在其自己的电话号码内部验证逻辑中已不再使用正则表达式

于 2018-10-31T17:03:48.247 回答
0

电话号码数据注解属性为数据类型,与数据显示格式无关。这只是一个误解。电话号码意味着您可以接受用于此语言环境的电话号码的数字和符号,但不检查格式、长度、范围等。对于显示字符串格式,使用 javascript 来进行更动态的用户交互,或者使用 MVC 掩码插件,或者正确使用显示格式字符串。

如果您是 MVC 编程的新手,请将此代码放在视图文件 (.cshtml) 的最后,看看它的神奇之处:

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#the_id_of_your_field_control").keyup(function () {
            $(this).val($(this).val().replace(/^(\d{2})(\d{5})(\d{4})+$/, "($1) $2-$3"));
        });
    });
</script>

这种格式目前用于巴西的移动电话。适应您的标准。

这会将括号和空格添加到您的字段中,这将增加输入数据的字符串长度。如果您只想保存数字,则必须在保存之前从字符串中删除非数字。

于 2020-07-11T19:06:20.587 回答