We know that ASP. NET MVC provides validation annotations for some forms, such as required attributes RequiredAttribute
However, this property does not fit the selection box's required
But most of the time, we need some of the required radio boxes.
For example, when the site registration, users need to agree to the site of some rules and so on
To do this, I encapsulated a Booleanrequiredattribute label class,
The class can be labeled with those boxes required
The specific classes are as follows:
Public classBooleanrequiredattribute:validationattribute, iclientvalidatable { Public BOOLValue {Get;Set; } Public Override BOOLIsValid (ObjectValue) {res = value! =NULL&& Value;returnRes;} PublicIenumerable<modelclientvalidationrule>getclientvalidationrules (Modelmetadata metadata, ControllerContext context) {Modelclientvalidation Rule Rule=NewModelclientvalidationrule {ValidationType="brequired", ErrorMessage=formaterrormessage (metadata. GetDisplayName ())}; Rule. Validationparameters.add ("BR", RES); yield returnrule; } Public BOOLres {Get;Set; } }
Supports client and server-side validation
Then the appearance needs to add a front-end JS verification method
Method is also very simple
// Boolean type must be checked function (value, element, param) { return element.checked;}); $.validator.unobtrusive.adapters.addsingleval ("brequired", "BR");
Just a few lines of code,
So, when we use the
You just need to label it on the entity.
Like what:
[booleanrequired] " required consent ")] Public BOOL Get set; }
Then above the view
<a id="showclause" href="javascript:void (0); "> website Terms of service </a> = m.agree) Agree   ; = M.agree)
Finally, we look at the effect
Isn't it practical? MVC's really pretty powerful.
You are welcome to expand more of these validation classes
Thanks for reading .....
ASP. NET MVC Validation Callout extension-checkbox required