我有以下用于自定义验证的类:
[AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=true)]
public sealed class RequiredIfAnyTrueAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} is required";
public List<string> OtherProperties { get; private set; }
public RequiredIfAnyTrueAttribute(string otherProperties)
: base(DefaultErrorMessage)
{
if (string.IsNullOrEmpty(otherProperties))
throw new ArgumentNullException("otherProperty");
OtherProperties = new List<string>(otherProperties.Split(new char[] { '|', ',' }));
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
foreach (string s in OtherProperties)
{
var otherProperty = validationContext.ObjectType.GetProperty(s);
var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
if (otherPropertyValue.Equals(true))
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredifanytrue"
};
clientValidationRule.ValidationParameters.Add("otherproperties", string.Join("|",OtherProperties));
return new[] { clientValidationRule };
}
}
我的视图模型是:
public class SampleViewModel
{
public bool PropABC { get; set; }
public bool PropXYZ { get; set; }
[RequiredIfAnyTrue("PropABC|PropXYZ")]
public int? TestField { get; set; }
}
当我的强类型视图呈现时,一切看起来都正常。如果选择了 PropABC 或 PropXYZ,那么我需要为 TestField 输入一个值。客户端和服务器端验证都是有效的。
但是,鉴于以下事件顺序:
- 检查 PropABC
- 提交表格
- 需要 TestField 的客户端验证触发
- 取消选中 PropABC
- 客户端验证不会重新触发,并且验证消息会一直保留到表单提交
为了解决#5,我通常会通过 jquery onread 将点击事件附加到复选框以重新启动验证。
在给定 MVC3 + unobtrusive + jquery 的情况下,是否有首选/推荐的手动强制客户端验证方式?