SHARE
TWEET

Untitled

a guest Feb 22nd, 2019 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class StudentViewModel
  2.     {
  3.         public int Id { get; set; }
  4.         public int Age { get; set; }
  5.         public bool IsGood { get; set; }
  6.        
  7.         [RequiredIf("IsGood", true)]
  8.         public string GoodIn { get; set; }
  9.        
  10.         [RequiredIf("IsGood", false)]
  11.         public string BadIn { get; set; }
  12.    }
  13.  
  14. public class RequiredIfAttribute : ValidationAttribute
  15.     {
  16.         RequiredAttribute _innerAttribute = new RequiredAttribute();
  17.         public string _dependentProperty { get; set; }
  18.         public object _targetValue { get; set; }
  19.  
  20.         public RequiredIfAttribute(string dependentProperty, object targetValue)
  21.         {
  22.             this._dependentProperty = dependentProperty;
  23.             this._targetValue = targetValue;
  24.         }
  25.         protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  26.         {
  27.             var field = validationContext.ObjectType.GetProperty(_dependentProperty);
  28.             if (field != null)
  29.             {
  30.                 var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
  31.                 if ((dependentValue == null && _targetValue == null) || (dependentValue.Equals(_targetValue)))
  32.                 {
  33.                     if (!_innerAttribute.IsValid(value))
  34.                     {
  35.                         string name = validationContext.DisplayName;
  36.                         return new ValidationResult(ErrorMessage = name + " Is required.");
  37.                     }
  38.                 }
  39.                 return ValidationResult.Success;
  40.             }
  41.             else
  42.             {
  43.                 return new ValidationResult(FormatErrorMessage(_dependentProperty));
  44.             }
  45.         }
  46.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top