asp.net mvc - Conditional rangevalidator +MVC -


in model of asp.net mvc application validate textbox required if specific checkbox checked.

something like

public bool retired {get, set};  [rangeif("retired",20,50)] public int retirementage {get, set}; 

how can that?

you need create custom validation attribute this:

public class rangeifattribute : validationattribute {     protected rangeattribute _innerattribute;      public string dependentproperty { get; set; }      public rangeifattribute(string dependentproperty, int minimum, int maximum)     {         _innerattribute = new rangeattribute(minimum, maximum);         dependentproperty = dependentproperty;     }      public rangeifattribute(string dependentproperty, double minimum, double maximum)     {         _innerattribute = new rangeattribute(minimum, maximum);         dependentproperty = dependentproperty;     }      public rangeifattribute(string dependentproperty, type type, string minimum, string maximum)     {         _innerattribute = new rangeattribute(type, minimum, maximum);         dependentproperty = dependentproperty;     }      public override string formaterrormessage(string name)     {         return _innerattribute.formaterrormessage(name);     }      protected override validationresult isvalid(object value, validationcontext validationcontext)     {         // reference property validation depends upon         var containertype = validationcontext.objectinstance.gettype();         var field = containertype.getproperty(dependentproperty);          if (field != null && field.propertytype.equals(typeof(bool)))         {             // value of dependent property                             var dependentvalue = (bool)(field.getvalue(validationcontext.objectinstance, null));              // if dependentvalue true...             if (dependentvalue)             {                 if (!_innerattribute.isvalid(value))                     // validation failed - return error                     return new validationresult(formaterrormessage(validationcontext.displayname), new[] { validationcontext.membername });             }         }          return validationresult.success;     } } 

then, can use in model in question.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -