Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class StudentViewModel
- {
- public int Id { get; set; }
- public int Age { get; set; }
- public bool IsGood { get; set; }
- [RequiredIf("IsGood", true)]
- public string GoodIn { get; set; }
- [RequiredIf("IsGood", false)]
- public string BadIn { 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;
- return new ValidationResult(ErrorMessage = name + " Is required.");
- }
- }
- return ValidationResult.Success;
- }
- else
- {
- return new ValidationResult(FormatErrorMessage(_dependentProperty));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement