|
| 1 | +using System; |
| 2 | +using System.ComponentModel.DataAnnotations; |
| 3 | +using System.Globalization; |
| 4 | +using System.Reflection; |
| 5 | + |
| 6 | +namespace BaGet.Core.Validation |
| 7 | +{ |
| 8 | + /// <summary> |
| 9 | + /// Provides conditional validation based on related property value. |
| 10 | + /// |
| 11 | + /// Inspiration: https://stackoverflow.com/a/27666044 |
| 12 | + /// </summary> |
| 13 | + [AttributeUsage(AttributeTargets.Property)] |
| 14 | + public sealed class RequiredIfAttribute : ValidationAttribute |
| 15 | + { |
| 16 | + #region Properties |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// Gets or sets the other property name that will be used during validation. |
| 20 | + /// </summary> |
| 21 | + /// <value> |
| 22 | + /// The other property name. |
| 23 | + /// </value> |
| 24 | + public string OtherProperty { get; } |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Gets or sets the display name of the other property. |
| 28 | + /// </summary> |
| 29 | + /// <value> |
| 30 | + /// The display name of the other property. |
| 31 | + /// </value> |
| 32 | + public string OtherPropertyDisplayName { get; set; } |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Gets or sets the other property value that will be relevant for validation. |
| 36 | + /// </summary> |
| 37 | + /// <value> |
| 38 | + /// The other property value. |
| 39 | + /// </value> |
| 40 | + public object OtherPropertyValue { get; } |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Gets or sets a value indicating whether other property's value should match or differ from provided other property's value (default is <c>false</c>). |
| 44 | + /// </summary> |
| 45 | + /// <value> |
| 46 | + /// <c>true</c> if other property's value validation should be inverted; otherwise, <c>false</c>. |
| 47 | + /// </value> |
| 48 | + /// <remarks> |
| 49 | + /// How this works |
| 50 | + /// - true: validated property is required when other property doesn't equal provided value |
| 51 | + /// - false: validated property is required when other property matches provided value |
| 52 | + /// </remarks> |
| 53 | + public bool IsInverted { get; set; } |
| 54 | + |
| 55 | + /// <summary> |
| 56 | + /// Gets a value that indicates whether the attribute requires validation context. |
| 57 | + /// </summary> |
| 58 | + /// <returns><c>true</c> if the attribute requires validation context; otherwise, <c>false</c>.</returns> |
| 59 | + public override bool RequiresValidationContext => true; |
| 60 | + |
| 61 | + #endregion |
| 62 | + |
| 63 | + #region Constructor |
| 64 | + |
| 65 | + /// <summary> |
| 66 | + /// Initializes a new instance of the <see cref="RequiredIfAttribute"/> class. |
| 67 | + /// </summary> |
| 68 | + /// <param name="otherProperty">The other property.</param> |
| 69 | + /// <param name="otherPropertyValue">The other property value.</param> |
| 70 | + public RequiredIfAttribute(string otherProperty, object otherPropertyValue) |
| 71 | + : base("'{0}' is required because '{1}' has a value {3}'{2}'.") |
| 72 | + { |
| 73 | + OtherProperty = otherProperty; |
| 74 | + OtherPropertyValue = otherPropertyValue; |
| 75 | + IsInverted = false; |
| 76 | + } |
| 77 | + |
| 78 | + #endregion |
| 79 | + |
| 80 | + /// <summary> |
| 81 | + /// Applies formatting to an error message, based on the data field where the error occurred. |
| 82 | + /// </summary> |
| 83 | + /// <param name="name">The name to include in the formatted message.</param> |
| 84 | + /// <returns> |
| 85 | + /// An instance of the formatted error message. |
| 86 | + /// </returns> |
| 87 | + public override string FormatErrorMessage(string name) |
| 88 | + { |
| 89 | + return string.Format( |
| 90 | + CultureInfo.CurrentCulture, |
| 91 | + ErrorMessageString, |
| 92 | + name, |
| 93 | + OtherPropertyDisplayName ?? OtherProperty, |
| 94 | + OtherPropertyValue, |
| 95 | + IsInverted ? "other than " : "of "); |
| 96 | + } |
| 97 | + |
| 98 | + /// <summary> |
| 99 | + /// Validates the specified value with respect to the current validation attribute. |
| 100 | + /// </summary> |
| 101 | + /// <param name="value">The value to validate.</param> |
| 102 | + /// <param name="validationContext">The context information about the validation operation.</param> |
| 103 | + /// <returns> |
| 104 | + /// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class. |
| 105 | + /// </returns> |
| 106 | + protected override ValidationResult IsValid(object value, ValidationContext validationContext) |
| 107 | + { |
| 108 | + if (validationContext == null) |
| 109 | + throw new ArgumentNullException(nameof(validationContext)); |
| 110 | + |
| 111 | + PropertyInfo otherProperty = validationContext.ObjectType.GetProperty(OtherProperty); |
| 112 | + if (otherProperty == null) |
| 113 | + { |
| 114 | + return new ValidationResult( |
| 115 | + string.Format(CultureInfo.CurrentCulture, "Could not find a property named '{0}'.", OtherProperty)); |
| 116 | + } |
| 117 | + |
| 118 | + object otherValue = otherProperty.GetValue(validationContext.ObjectInstance); |
| 119 | + |
| 120 | + // check if this value is actually required and validate it |
| 121 | + if (!IsInverted && Equals(otherValue, OtherPropertyValue) || |
| 122 | + IsInverted && !Equals(otherValue, OtherPropertyValue)) |
| 123 | + { |
| 124 | + if (value == null) |
| 125 | + return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); |
| 126 | + |
| 127 | + // additional check for strings so they're not empty |
| 128 | + if (value is string val && val.Trim().Length == 0) |
| 129 | + return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); |
| 130 | + } |
| 131 | + |
| 132 | + return ValidationResult.Success; |
| 133 | + } |
| 134 | + } |
| 135 | +} |
0 commit comments