您可以创建自己的自定义验证属性或使用MVC Foolproof Validation,然后执行以下操作:
class MyClass
{
public int Selector {get;set;} // 1 or 2
[RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")]
public string A_required_for_1 {get;set;}
[RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")]
public string B_required_for_1 {get;set;}
[RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")]
public string C_required_for_2 {get;set;}
[RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")]
public string D_required_for_2 {get;set;}
[Required("Your Error Message")]
public string E_Required_for_both_selectors {get;set;}
}
正如 Win 所提到的,它似乎已经有一段时间没有积极开发了,所以您可能想要沿着创建自己的自定义验证属性的路线走下去,这确实需要更多的工作,但您可以更好地控制验证本身。根据您的需要选择。
对于自定义验证属性,您可以执行以下操作:
public class RequiredIfOtherProperty : ValidationAttribute
{
private readonly string _otherPropertyName;
private readonly string _compareValue;
public RequiredIfOtherProperty(string otherPropertyName, string compareValue)
{
_otherPropertyName = otherPropertyName;
_compareValue = compareValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherProperty = validationContext.ObjectType.GetProperty(_otherPropertyName);
if (otherProperty == null)
{
return new ValidationResult($"Property '{_otherPropertyName}' does not exist");
);
var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
if (!_compareValue.Equals(otherPropertyValue))
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
它应该让您大致了解可以做什么,并且您可以将实际验证更改为您喜欢的任何方式。然后您可以像使用普通属性一样使用它,例如
[RequiredIfOtherProperty("SomeProperty", "ValueToCompareWith")]