您可以创建自己的自定义验证属性或使用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;}
}
似乎正如赢提到不一直在积极发展了一段时间,所以你可能会想要去沿着创建自己的自定义验证属性的路线,这需要更多的工作,但您可以更好地控制验证本身。根据您的需要选择。
对于一个自定义的验证属性,你可以做这样的事情:
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")]
这是‘在某些情况下禁用需要确认属性’不是复制 –
请你帮个忙和独立的编辑和你的应用程序中创建功能。 – Programmer
@NicholasKinney我不明白你为什么评论适用于这个问题。你能澄清一下吗? –