.net - Class-level validation -


i validating class dataannotations utils.

i have class has title property , item property. want apply requiredattribute title property should invalid if item property null; if item property set object, title not required.

in short words, want requiredattribute validate if condition in class satisfied.

how can done.

update

as didn't find other way, , since don't need functionality often, decided make rough way using class-level validator. question then, there way manually update ui make title textbox red frame, i.e. invalidate it?

update 2
want class-level validator summarize on field. example, have fields cost , salesprice, wanna make sure salesprice > cost , invalidate salesprice otherwise, don't want global validation error on class level.

i prefer xamly way.

you may able creating custom validation attribute class. unfortunately dataannotation attributes assigned properties cannot access other properties of parent class far aware hence need create class validator.
using system.componentmodel.dataannotations namespace need create custom attribute class inheriting validationattribute , override isvalid method (i have not tested code below should going):

[attributeusage(attributetargets.class, allowmultiple = false)] sealed public class customattribute: validationattribute {   public customattribute()   {   }    public override bool isvalid(object value)   {      if(value myclass)      {        return ((myclass)value).item != null &&          string.isnullorempty(((myclass)value).title) ? false : true;      }      else return true;   } } 

digging little further appears whilst cross field validation not possible out of box can achieved extending framework support it. see this article details, added future versions of mvc.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -