简体   繁体   中英

MVC DataAnnotation RequiredIfNot

I would need help to ensure CustomerCode has value only if UserTypeID is not 1

    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. EmployeeCode is required if UserTypeID is 1 (this part is working fine)
  2. CustomerCode is required if UserTypeID is not 1 (this part is not working)

As per explain by Yong Shun, the logic does not affected by ".": I have change the IsValid() function as per below and now its working:


        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));
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM