Featured post
validation - An ASP.NET MVC validator to make sure at least one checkbox is checked -
i have asp.net mvc 2 project in i've created data transfer object receive data web page form. form has 2 groups of checkboxes on it. want validate object make sure @ least 1 of checkboxes in each group checked.
i'm doing validation on server side user won't able hack around client-side validation. (i add client-side validation jquery later; that's easy.)
my understanding have create own custom validationattribute data transfer object class, don't understand how create , use 1 can accept arbitrary list of checkbox properties make sure @ least 1 of them true. guessing have call attributes this:
[atleastonecheckbox("set1check1", "set1check2", "set1check3", errormessage = "you must check @ least 1 checkbox in set 1.")] [atleastonecheckbox("set2check1", "set2check2", "set2check3", "set2check4", "set2check5", errormessage = "you must check @ least 1 checkbox in set 2.")] public class myformdto { ... }
what implementation of atleastonecheckboxattribute like?
or there different way should kind of validation?
if have several checkbox groups, need deine attribute several times.
[attributeusage( attributetargets.class)] public class atleastonecheckboxattribute : validationattribute { private string[] _checkboxnames; public atleastonecheckboxattribute(params string[] checkboxnames) { _checkboxnames = checkboxnames; } protected override validationresult isvalid(object value, validationcontext validationcontext) { var propertyinfos = value.gettype().getproperties(bindingflags.public | bindingflags.instance) .where(x=>_checkboxnames.contains(x.name)); var values = propertyinfos.select(x => x.getgetmethod().invoke(value, null)); if (values.any(x => convert.toboolean(x))) return validationresult.success; else { errormessage = "at least 1 checkbox must selected"; return new validationresult(errormessage); } } }
update
as have found out, class-level validation called after properties pass. in order error, just use empty string key.
- Get link
- X
- Other Apps
Comments
Post a Comment