MVC DataAnnotation RequiredIfNot



只有当UserTypeID不是1 时,我才需要帮助确保CustomerCode有值

public class FilteringViewModel
{
[Required]
public int? UserID { get; set; }
[Required]
public string UserTypeID { get; set; }
[RequiredIf("UserTypeID", "1")]
public string EmployeeCode { get; set; }
[RequiredIf("UserTypeID", "!1")]
public string CustomerCode { get; set; }
}
public class RequiredIfAttribute : ValidationAttribute
{
RequiredAttribute _innerAttribute = new RequiredAttribute();
public string _dependentProperty { get; set; }
public object _targetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
this._dependentProperty = dependentProperty;
this._targetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var field = validationContext.ObjectType.GetProperty(_dependentProperty);
if (field != null)
{
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
if ((dependentValue == null && _targetValue == null) || (dependentValue.Equals(_targetValue)))
{
if (!_innerAttribute.IsValid(value))
{
string name = validationContext.DisplayName;
string specificErrorMessage = ErrorMessage;
if (string.IsNullOrEmpty(specificErrorMessage))
specificErrorMessage = $"{name} is required.";
return new ValidationResult(specificErrorMessage, new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
else
{
return new ValidationResult(FormatErrorMessage(_dependentProperty));
}
}
}
  1. 如果UserTypeID为1,则需要EmployeeCode(此部分工作正常(
  2. 如果UserTypeID不是1(此部分不起作用(,则需要CustomerCode

根据永顺的解释,逻辑不受"的影响&";。我已经根据以下内容更改了IsValid((函数,现在它正在工作:


protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var field = validationContext.ObjectType.GetProperty(_dependentProperty);
if (field != null)
{
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
if (
(dependentValue == null && _targetValue == null)
|| (!_targetValue.ToString().StartsWith("!") && dependentValue.Equals(_targetValue))
|| (_targetValue.ToString().StartsWith("!") && !dependentValue.Equals(_targetValue.ToString().Substring(1)))
)
{
//this statement means that we will proceed to do the validation
if (!_innerAttribute.IsValid(value))
{
string name = validationContext.DisplayName;
string specificErrorMessage = ErrorMessage;
if (string.IsNullOrEmpty(specificErrorMessage))
specificErrorMessage = $"{name} is required.";
return new ValidationResult(specificErrorMessage, new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
else
{
return new ValidationResult(FormatErrorMessage(_dependentProperty));
}
}

最新更新