CryoFusion87
CryoFusion87

Reputation: 796

MVC 4 Validate a checkbox without using JQuery

I am currently trying to validate a Terms and Conditions checkbox on a payment form so that the form is not submitted until the terms and condition checkbox is checked.

The particular form that I am creating is only going to be used by a group of clients who use IE6 (therefore I cannot validate using JQuery).

I have decorated the terms and conditions bool model value with the required data annotation but the required error message is not displayed ( unlike other values that use either string, decimal or int etc.

I have managed to get an error to display using this code:

if (ModelState.IsValid && model.TermsAndConditions)
            {
                ConnectAndRedirectoToProtx(model);
            }
            else
            {
                //store locally and sort later
                TempData["message"] = "You must first read through and agree to the terms and conditions";
            }

this code is found in the HttpPost Index ActionResult of the controller I then render in the View like this:

div style="color: red;font-weight:bold;">@TempData["message"]</div>

the issue with using this cpde is that it only shows if all the other fields are correct, is it possible without using JQuery to display this error message along with the other error messages that show immediately after the submit button is clicked?

Upvotes: 1

Views: 703

Answers (1)

Niraj
Niraj

Reputation: 1842

Required data annotation tag will not work in your case as even a unchecked check box passes a false value to Model. If JQuery is not supported you can use Java Script(Until this is also blocked by the browser.) visit following link for your help.

http://www.w3schools.com/js/js_form_validation.asp

Further you can change your controller function like following to track the error only for this case

if(!model.TermsAndConditions)
{
    TempData["message"] = "You must first read through and agree to the terms and conditions";
}

if (ModelState.IsValid)
        {
            ConnectAndRedirectoToProtx(model);
        }
        else
        {
            //store locally and sort later
            TempData["message"] = "Invalid Model or some other error message......";
        }

Upvotes: 1

Related Questions