Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have to use custom validation attribute for this.</p> <p>Here is the sample code</p> <p>public class RequiredIfAttribute : RequiredAttribute { private String PropertyName { get; set; } private Object DesiredValue { get; set; }</p> <pre><code> 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 enum UserType { Admin, Regular } 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