Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I had the same problem yesterday but I did it in a very clean way which works for both client side and server side validation.</p> <p>Condition: Based on the value of other property in the model, you want to make another property required. Here is the code</p> <pre><code>public class RequiredIfAttribute : RequiredAttribute { private String PropertyName { get; set; } private Object DesiredValue { get; set; } public RequiredIfAttribute(String propertyName, Object desiredvalue) { PropertyName = propertyName; DesiredValue = desiredvalue; } protected override ValidationResult IsValid(object value, ValidationContext context) { Object instance = context.ObjectInstance; Type type = instance.GetType(); Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null); if (proprtyvalue.ToString() == DesiredValue.ToString()) { ValidationResult result = base.IsValid(value, context); return result; } return ValidationResult.Success; } } </code></pre> <p>Here PropertyName is the property on which you want to make your condition DesiredValue is the particular value of the PropertyName (property) for which your other property has to be validated for required</p> <p>Say you have the following</p> <pre><code>public class User { public UserType UserType { get; set; } [RequiredIf("UserType", UserType.Admin, ErrorMessageResourceName = "PasswordRequired", ErrorMessageResourceType = typeof(ResourceString))] public string Password { get; set; } } </code></pre> <p>At last but not the least , register adapter for your attribute so that it can do client side validation (I put it in global.asax, Application_Start)</p> <pre><code> DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),typeof(RequiredAttributeAdapter)); </code></pre>
 

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