提问人:Hunter Tran 提问时间:11/27/2017 最后编辑:Hunter Tran 更新时间:11/27/2017 访问量:922
如何使用 DataAnnotations 修饰父属性,但验证子属性
How can I decorate parent with DataAnnotations, but validate for child property
问:
假设我有一个 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 的验证规则,而不是它的 Value。
这是正确的方法吗?
谢谢
答: 暂无答案
上一个:如何手动添加MVC客户端验证?
下一个:数据验证实施
评论
ValidationContext
CustomField
int ValueLength
FirstViewModel
SecondViewModel