Asp.net mvc 3 实现RequiredIf和RequiredIfNot属性验证器,这取决于两个值

Asp.net mvc 3 实现RequiredIf和RequiredIfNot属性验证器,这取决于两个值,asp.net-mvc-3,Asp.net Mvc 3,我需要实现一个RequiredIF验证器,它依赖于两个值,一个复选框和一个从下拉列表中选择的值。 如果可能的话,我需要 [RequiredIf("Property1", true,"Property2,"value", ErrorMessageResourceName = "ReqField", ErrorMessageResourceType = typeof(RegisterUser))] 您必须定制验证器。这是实现这一目标的必经之路。我希望这会有所帮助以下是创建您自己的Require

我需要实现一个RequiredIF验证器,它依赖于两个值,一个复选框和一个从下拉列表中选择的值。 如果可能的话,我需要

  [RequiredIf("Property1", true,"Property2,"value", ErrorMessageResourceName = "ReqField", ErrorMessageResourceType = typeof(RegisterUser))]

您必须定制验证器。这是实现这一目标的必经之路。我希望这会有所帮助

以下是创建您自己的RequiredIf和RequiredIfNot自定义验证器的代码。 如果要检查2个值,只需添加额外代码

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;
    }
}
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;
    }
}
[RequiredIf("IsRequired", true, ErrorMessage = "First Name is required.")]