Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I just did something similar in an attribute I called "RequiredIfTrueAttribute". This will get you the value of the other property in the model. Pass the other property name as a string into the custom attribute constructor.</p> <pre><code>public class RequiredIfTrueAttribute: ValidationAttributeBase { public string DependentPropertyName { get; private set; } public RequiredIfTrueAttribute(string dependentPropertyName) : base() { this.DependentPropertyName = dependentPropertyName; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { // Get the property we need to see if we need to perform validation PropertyInfo property = validationContext.ObjectType.GetProperty(this.DependentPropertyName); object propertyValue = property.GetValue(validationContext.ObjectInstance, null); // ... logic specific to my attribute return ValidationResult.Success; } } </code></pre> <p>Now if only there was a way to pass the dependentPropertyName to the validation attribute without using a string...</p> <hr> <p><em>Update:</em></p> <p>In C# 6.0 there is now a way to call the dependentPropertyName without using a string. Simply use nameof(thePropertyName) and it will be replaced with the string. This happens in compile time so if you change the property name you will immediately know that you need to change this as well. Or, even better, if you do a <kbd>Ctrl</kbd>+<kbd>R</kbd>, <kbd>Ctrl</kbd>+<kbd>R</kbd> to rename the variable it will automatically rename the version inside the nameof as well. Awesome!</p> <p>See: <a href="https://msdn.microsoft.com/en-us/library/dn986596%28v=vs.140%29.aspx" rel="nofollow noreferrer">nameof (C# and Visual Basic Reference)</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload