【问题标题】:Regular expression using Data Annotations in C#在 C# 中使用数据注释的正则表达式
【发布时间】:2014-02-27 00:15:45
【问题描述】:

我需要使用 C# MVC 4 Data Annotations 验证 3 种类型:

» public int Quantidade { get; set; }

Values to accept: ex. 10 all the rest need to present a custom message

» public decimal Valor { get; set; } 

Portuguese Currency ex. 10 or 10.20 all the rest need to present a custom message

» public string PesoBruto { get; set; }

Weight ex. 100 or 100.200 all the rest need to present a custom message

所有这些都是自定义消息所必需的。

有什么想法吗?

谢谢。

【问题讨论】:

    标签: c# regex model-view-controller


    【解决方案1】:

    我不确定您在问什么,是为您编写正则表达式还是如何将正则表达式验证应用于类属性。如果你需要正则表达式我建议你使用这个网站自己写一个(一旦你熟悉了正则表达式应该不会太难):

    http://www.regexr.com/

    至于带有数据注释的验证部分,你所要做的就是用正则表达式属性装饰你的模型:

    public class MyModel
    {
       [Required, RegularExpression("pattern_to_match", ErrorMessage="Your custom message")]
       public string Valor { get; set; }
    }
    

    请注意,您需要包含以下命名空间:System.ComponentModel.DataAnnotations

    【讨论】:

    【解决方案2】:
    [RegularExpression(@"\d*[1-9]\d*", ErrorMessage = "Valor inválido.")]
    public int Quantidade { get; set; }
    

    有效:1 / 0100 / 0999 无效:0 / 0.9 / 0,9

    [RegularExpression(@"^(?!0\d|$)\d*(\.\d{1,2})?$", ErrorMessage = "Valor inválido.")]
    public decimal Valor { get; set; } 
    

    有效期:01 / 0100 / 0999 / 01.00 / 1.01 无效:0 / 0.900 / 0,900

    [RegularExpression(@"^(?!0\d|$)\d*(\.\d{1,3})?$", ErrorMessage = "Valor inválido.")]
    public string PesoBruto { get; set; }
    

    有效:01 / 0100 / 0999 / 01.000 / 1.011 无效:0 / 0.9001 / 0,9001

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 2015-01-25
      • 2014-07-26
      • 2011-11-25
      • 1970-01-01
      相关资源
      最近更新 更多