我想使用ComponentModel DataAnnotations验证两个属性中至少有一个具有值。我的模型看起来像这样:
public class FooModel {
public string Bar1 { get; set; }
public int Bar2 { get; set; }
}
基本上,我想验证FooModel,以便需要Bar1 或 Bar2 。换句话说,你可以输入一个,或另一个,或两者,但你不能把它们都留空。
我希望这对于服务器端和不显眼的客户端验证都有效。
编辑:这可能是possible duplicate, as this looks similar to what I'm looking to do
答案 0 :(得分:6)
如果要抽取自定义JavaScript进行验证,则需要扩展ValidationAttribute类并覆盖IsValid方法,并实现IClientValidatable。如下所示。
[AttributeUsage(AttributeTargets.Property)]
public sealed class AtLeastOneOrTwoParamsHasValue : ValidationAttribute, IClientValidatable
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var param1 = validationContext.ObjectInstance.GetType().GetProperty("Param1").GetValue(value, null);
//var param2 = validationContext.ObjectInstance.GetType().GetProperty("Param2").GetValue(value, null);
//DO Compare logic here.
if (!string.IsNullOrEmpty(Convert.ToString(param1)))
{
return ValidationResult.Success;
}
return new ValidationResult("Some Error");
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
//Do custom client side validation hook up
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "validParam"
};
}
}
用法:
[AtLeastOneOrTwoParamsHasValue(ErrorMessage="Atleast one param must be specified.")]