如何使用DataAnnotations装饰父级,但验证子属性

时间:2017-11-27 06:48:57

标签: c# asp.net-mvc validation client-side

我们说我有一个CustomField类,如下所示

public class CustomField
{
    public string Value { get; set; }
}

然后我有多个ViewModel类,每个类都用于另一种类型的表单

public class FirstViewModel
{
    public CustomField Title { get; set; }
}

public class SecondViewModel
{
    public CustomField Subject { get; set; }
}

如何将数据注释放在ViewModel的子属性上,但实际上是否验证了CustomField的子属性?

例如,我可以用不同的数据注释装饰Title和Subject,它将根据数据注释验证CustomField的Value属性

public class FirstViewModel
{
    [CustomFieldStringLength(20, MinimumLength = 2, ErrorMessage = "string length must between 2 and 20")]
    public CustomField Title { get; set; }
}

public class SecondViewModel
{
    [CustomFieldStringLength(30, MinimumLength = 2, ErrorMessage = "string length must between 2 and 30")]
    public CustomField Subject { get; set; }
}

我尝试过:

重写StringLengthAttribute,它将在服务器端

上运行
public class CustomFieldStringLengthAttribute : StringLengthAttribute
{
    public CustomFieldStringLengthAttribute(int maximumLength) : base(maximumLength)
    {
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        CustomFieldValue customFieldValue = (CustomFieldValue)value;
        return base.IsValid(customFieldValue.Value, validationContext);
    }
}

获取默认适配器以生成正确的客户端验证器

public class CustomFieldStringLengthAdapter : DataAnnotationsModelValidator<CustomFieldStringLengthAttribute>
{
    public CustomFieldStringLengthAdapter(
        ModelMetadata metadata,
        ControllerContext context,
        CustomFieldStringLengthAttribute attribute) : base(metadata, context, attribute)
    {
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        return new[] { new ModelClientValidationStringLengthRule(ErrorMessage, Attribute.MinimumLength, Attribute.MaximumLength) };
    }
}

// Register in Global.asax.cs Application_Start

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomFieldStringLengthAttribute), typeof(CustomFieldStringLengthAdapter));

对于客户端,它仍然会生成CustomField的验证规则,而不是它的值。

这是正确的方法吗?

由于

0 个答案:

没有答案