Verify that the checkbox must be checked in ASP. Validation of required checkbox in ASP.

Source: Internet
Author: User

Reprinted from Http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc/

Why would want to has a required checkbox, i.e. a checkbox that user would has to check? Well, a typical example would is that and you had some sort of terms associated with submitting a form that the user had to a Gree to.

You might think this decorating a Boolean property on one of the your MVC models with a requiredattribute, would mean if You presented. Your view as a checkbox, that would require the user to click the checkbox before Submitti ng the form. This isn't the case however. If a look at the implementation of the RequiredAttribute it's actually casting the value to validate into a stri Ng and checking the string length. If it can ' t cast the value to a string, it'll just return true for IsValid.

It's quite easy however to create your own custom validation attribute so you could decorate your the Boolean property with . The following code checks if the decorated property was a bool, and if so, requires it to has been set to true;

 Public classBooleanrequiredattribute:validationattribute, iclientvalidatable{ Public Override BOOLIsValid (Objectvalue) {        if(Value is BOOL)            return(BOOL) value; Else            return true; }     PublicIenumerable<modelclientvalidationrule>getclientvalidationrules (Modelmetadata metadata, ControllerContext context) {yield return NewModelclientvalidationrule {errormessage=formaterrormessage (metadata. GetDisplayName ()), ValidationType="booleanrequired"                            }; }}

Notice the getclientvalidationrules-method above where we specify the error message to display if Client-side validation f Ails, and what's the validation type is. The value we provide as the validation type would be rendered as the name of the rule in the the HTML element, and would be used Further down-to-tell of the JQuery how-to validate the property.

After creating the new validation attribute, we need to apply it to a Boolean property on out model;

" You must accept the terms and conditions. "  "I accept the terms and conditions")]publicbool  Getset; }

Next, create a simple view with a form that includes your Boolean property;

@model [email protected] (Html.BeginForm ()) {<fieldset> <legend>terms and Conditions</legend>@Html. ValidationSummary (true,"Please correct the errors and try again.")        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce facilisis ullamcorper consequat.            Vestibulum non sapien lectus.        Nullam at quam EU sapien mattis ultrices. </p> <ol> <li>@Html. checkboxfor (M=m.termsandconditionsaccepted) @Html. Labelfor (M= m.termsandconditionsaccepted,New{@class ="checkbox"}) @Html. validationmessagefor (M=m.termsandconditionsaccepted)</li> </ol> <input type="Submit"Value="Submit"/> </fieldset>}

Lastly, in order for client-side validation to work, you need to include the following script in your view (or can jus T put line 3 in a JavaScript file so you reference);

<script type= "Text/javascript" >    (function  ($) {        $. Validator.unobtrusive.adapters.addBool ("booleanrequired", "required");    } (JQuery)); </script>

This just registers a new validation adapter for the Boolean required attribute, where the first parameter is the adapter Name and the second parameter is the name of the JQuery validate rule. The adapter name should match the value we specified earlier as the validation type, and the JQuery validation Required-ru Le'll require the user to check the checkbox.

That ' s it! This would make sure that the checkbox was checked by the user client-side (using JQuery unobtrusive validation*) and that T The He Boolean property was set to True server-side when the form was submitted to the server.

*the clientvalidationenabled and unobtrusivejavascriptenabled application settings must bes set to true in your Web. config For client-side validation to work.

Verify that the checkbox must be checked in ASP. Validation of required checkbox in ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.