【问题标题】:Phone validation attribute not working电话验证属性不起作用
【发布时间】:2017-12-13 12:22:58
【问题描述】:

我正在尝试验证一些用户联系方式,如下所示:

public class Customer
{
    [Display(Name = "Your e-mail :")]
    [Required(ErrorMessage = "An email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string ContactEmail { get; set; }    

    [Display(Name = "Your contact number :")]
    [Required(ErrorMessage = "A phone number is required")]
    [Phone(ErrorMessage = "Invalid Phone Number")] 
    public string ContactNumber { get; set; }

}

在我看来,电子邮件验证效果很好,并且只允许有效的电子邮件地址。但是,电话验证根本不起作用,它允许各种字母和特殊字符。

文档指出PhoneAttribute

使用电话号码的正则表达式指定数据字段值是格式正确的电话号码

那为什么没有发生呢?

【问题讨论】:

  • 我同意 Vignesh,不要使用默认的 Phone 数据注释。它永远不会像我们想要的那样运作,文化也不会像我们想要的那样运作。我建议您使用自己的正则表达式创建自己的
  • 是否可以有 RegexOptions.Compiled |正则表达式选项.IgnoreCase | RegexOptions.ExplicitCapture 反映在字符串中?

标签: c# asp.net-mvc model-validation


【解决方案1】:

使用以下代码进行电话验证。

[Display(Name = "Your contact number :")]
[Required(ErrorMessage = "A phone number is required.")]
[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
[RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Invalid Phone Number.")]
public string ContactNumber { get; set; }

【讨论】:

  • 这就是我最终做的,可惜 PhoneAttribute 不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 2020-03-26
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
相关资源
最近更新 更多