【问题标题】:Apply data annotations validation to all properties of same primitive datatype in a viewmodel将数据注释验证应用于视图模型中相同原始数据类型的所有属性
【发布时间】:2019-08-02 07:58:59
【问题描述】:

我在 google 和 SO 中搜索了我的场景,但找不到答案。我想在 double 类型的 viewmodel 类属性中创建正则表达式数据注释验证。因为我有大约 20 个 double 类型的属性。因此,我想创建一个自定义正则表达式验证并应用于所有双精度类型属性,而无需明确指定每个属性,例如:

[RegularExpression(@"^[0-9]{1,6}(\.[0-9]{1,2})?$", ErrorMessage ="Invalid Input")]
public double Balance { get; set; }

我期待这样的事情:

[ApplyRegExpToAllDoubleTypes]
public class MyModel
{
     public double Balance { get; set; }
     public double InstallmentsDue { get; set; }
}

【问题讨论】:

  • 我不认为这是可能的......
  • Ehrm...double 是一个数字。正则表达式用于字符串。这对你有什么影响?您的正则表达式正在验证输入是带小数点的数字。但是拥有double 类型的属性已经为您做到了——框架会进行检查。为什么需要双精度正则表达式?
  • 另外,您确定要在Balance 变量上使用double 吗?我觉得这和钱有关。 decimalstackoverflow.com/a/1165788/809357 更好地代表金钱

标签: c# validation data-annotations asp.net-mvc-5.2


【解决方案1】:

这是一个有趣的问题。以下是它的实现方法:

定义一个自定义ValidationAttribute 并通过设置AttributeTargets.Class 在类级别应用它。在ValidationAttribute 内部,使用反射获取double 属性,然后验证每个属性的值。如果任何验证失败,则返回验证失败消息。

[ApplyRegExpToAllDoubleTypes]
public class MyModel {
    public double Balance { get; set; }
    public double InstallmentsDue { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class ApplyRegExpToAllDoubleTypes : ValidationAttribute {
    protected override ValidationResult IsValid(object currentObject, ValidationContext validationContext) {
        if (currentObject == null) {
            return new ValidationResult("Object can't be null");
        }

        var properties = validationContext.ObjectType.GetProperties().Where(x => x.PropertyType == typeof(double));
        foreach (var property in properties) {
            //Here I compare the double property value against '5'
            //Replace the following with the custom regex check
            if ((double)property.GetValue(currentObject) < 5) {
                return new ValidationResult("All double properties must be greater than 5");
            }
        }
        return ValidationResult.Success;
    }
}

【讨论】:

  • 是的,您将验证应用于类型的所有属性。但是这个问题询问关于双重正则表达式验证(这没有意义)。
  • @trailmax 问题是关于将验证应用于多个属性而不必注释类中的每个属性。我没有在我的答案中包含 OP 的正则表达式,因为它与问题的要点无关(因为我关心给定的正则表达式可能是无效的正则表达式)。而且一般来说RegularExpression可以用来对double类型设置一些验证规则,所以我不确定你的意思是什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-08
相关资源
最近更新 更多