【问题标题】:RegularExpression Attribute - Passing in a property field of a class正则表达式属性 - 传入类的属性字段
【发布时间】:2014-02-15 21:01:37
【问题描述】:

我创建了一个 MobileNumberAnnotation 类,它具有指定正则表达式的属性。现在,当我指定 RegularExpressionAttribute 时,如何告诉它获取此属性的值作为模式?

public class MobileNumberAnnotation
{
    public string MobileFormat = "^(07(\\d ?){9})";
}

我尝试执行以下操作,但我不知道为什么它不起作用,因为它需要一个字符串模式。

    [Required]
    [RegularExpressionAttribute(MobileNumberAnnotation.MobileFormat)]
    public int MobileNumber { get; set; }

【问题讨论】:

    标签: c# regex asp.net-mvc validation attributes


    【解决方案1】:

    你可以这样做:

    [RegularExpression("^(07(\\d ?){9})", ErrorMessage = "Invalid Phone Number")]
    

    【讨论】:

    • *假设您正确编写正则表达式。
    • 我知道你能做到。不过还是谢谢你的帮助
    【解决方案2】:

    如果您将 MobileFormat 的声明更改为 const,这应该可以解决问题

    public const string MobileFormat = "^(07(\\d ?){9})";
    

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      相关资源
      最近更新 更多