问题
I need to implement a RequiredIF validator which depends on two values, a checkbox and a value selected from a dropdown. I need if possible something like
[RequiredIf("Property1", true,"Property2,"value", ErrorMessageResourceName = "ReqField", ErrorMessageResourceType = typeof(RegisterUser))]
回答1:
You have to make custom validator. it is the bets way to achieve that. I hope this helps custom validator
回答2:
Here is code to create your own RequiredIf and RequiredIfNot Custom Validator. Simply add additional code if you want to check for 2 values.
RequiredIf
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
private readonly RequiredAttribute _innerAttribute = new RequiredAttribute();
internal string _dependentProperty;
internal object _targetValue;
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
_dependentProperty = dependentProperty;
_targetValue = targetValue;
}
/// <summary>
/// Returns if the given validation result is valid. It checks if the RequiredIfAttribute needs to be validated
/// </summary>
/// <param name="value">Value of the control</param>
/// <param name="validationContext">Validation context</param>
/// <returns></returns>
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.ToString() == _targetValue.ToString()))
{
if (!_innerAttribute.IsValid(value))
{
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
}
else
{
throw new ValidationException("RequiredIf Dependant Property " + _dependentProperty + " does not exist");
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "requiredif",
};
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(_dependentProperty);
rule.ValidationParameters["desiredvalue"] = _targetValue is bool ? _targetValue.ToString().ToLower() : _targetValue;
yield return rule;
}
}
RequireIfNot:
public class RequiredIfNotAttribute : ValidationAttribute, IClientValidatable
{
private readonly RequiredAttribute _innerAttribute = new RequiredAttribute();
internal string _dependentProperty;
internal object _targetValue;
public RequiredIfNotAttribute(string dependentProperty, object targetValue)
{
_dependentProperty = dependentProperty;
_targetValue = targetValue;
}
/// <summary>
/// Returns if the given validation result is valid. It checks if the RequiredIfAttribute needs to be validated
/// </summary>
/// <param name="value">Value of the control</param>
/// <param name="validationContext">Validation context</param>
/// <returns></returns>
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.ToString() != _targetValue.ToString()))
{
if (!_innerAttribute.IsValid(value))
{
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
}
else
{
throw new ValidationException("RequiredIfNot Dependant Property " + _dependentProperty + " does not exist");
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "requiredifnot",
};
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(_dependentProperty);
rule.ValidationParameters["desiredvalue"] = _targetValue is bool ? _targetValue.ToString().ToLower() : _targetValue;
yield return rule;
}
}
Usage: In your model use the following DataAnnotation.
[RequiredIf("IsRequired", true, ErrorMessage = "First Name is required.")]
来源:https://stackoverflow.com/questions/13059520/implement-a-requiredif-and-requiredifnot-attribute-validator-which-depends-on-t