RequiredIf Conditional Validation Attribute

后端 未结 6 1165
长发绾君心
长发绾君心 2020-11-22 15:19

I was looking for some advice on the best way to go about implementing a validation attribute that does the following.

Model

public class MyInputMode         


        
6条回答
  •  天涯浪人
    2020-11-22 15:59

    Expanding on the notes from Adel Mourad and Dan Hunex, I amended the code to provide an example that only accepts values that do not match the given value.

    I also found that I didn't need the JavaScript.

    I added the following class to my Models folder:

    public class RequiredIfNotAttribute : ValidationAttribute, IClientValidatable
    {
        private String PropertyName { get; set; }
        private Object InvalidValue { get; set; }
        private readonly RequiredAttribute _innerAttribute;
    
        public RequiredIfNotAttribute(String propertyName, Object invalidValue)
        {
            PropertyName = propertyName;
            InvalidValue = invalidValue;
            _innerAttribute = new RequiredAttribute();
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);
    
            if (dependentValue.ToString() != InvalidValue.ToString())
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
                }
            }
            return ValidationResult.Success;
        }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "requiredifnot",
            };
            rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
            rule.ValidationParameters["invalidvalue"] = InvalidValue is bool ? InvalidValue.ToString().ToLower() : InvalidValue;
    
            yield return rule;
        }
    

    I didn't need to make any changes to my view, but did make a change to the properties of my model:

        [RequiredIfNot("Id", 0, ErrorMessage = "Please select a Source")]
        public string TemplateGTSource { get; set; }
    
        public string TemplateGTMedium
        {
            get
            {
                return "Email";
            }
        }
    
        [RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Campaign")]
        public string TemplateGTCampaign { get; set; }
    
        [RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Term")]
        public string TemplateGTTerm { get; set; }
    

    Hope this helps!

提交回复
热议问题