0

I have an MVC application with a model property as follows:

        [Display(Name = "Terms and Conditions")]
        [Range(typeof(bool), "true", "true", ErrorMessage = "You gotta tick the box!")]
        public bool AcceptTerms { get; set; }

I am trying to add validation to display a message when it is not clicked but regardless of whether it is clicked or not the error message always displays and so I cannot pass this form, view is as follows:

<div class="form-group">
  @Html.Label("Accept Terms", htmlAttributes: new { @class = "control-label col-md-4" })
  <div class="col-md-8">
    <div class="checkbox">
       @Html.EditorFor(x => x.AcceptTerms)
       @Html.ValidationMessageFor(x => x.AcceptTerms)
     </div>
    </div>
</div>

What am I doing wrong here?

Jay
  • 3,012
  • 14
  • 48
  • 99
  • 2
    You need to create your own `ValidationAttribute` (and implement `IClientValidatable` if you want client side validation as well) - refer [this answer by dazbradbury](http://stackoverflow.com/questions/4730183/mvc-model-require-true) –  Nov 21 '16 at 11:29
  • I have tried using the isTrue method but again the message is failing to be taken away regardless of whether my checkbox is checked – Jay Nov 21 '16 at 12:07
  • Again - you need to create your own validation attribute! You cannot use a `RangeAttribute` for 2 reasons. First if you look at the html - it generates the `data-*` values as `"True"` (capital `"T"`) which does not match the value of your checkbox which is lower case `"true"` Although you could use `(typeof(string)`, but that would not solve anything since the `$.validator` will check the value of the checkbox which is `true` so you will never get a validation error –  Nov 21 '16 at 12:11
  • var validator = $("#WizardForm").validate(); // obtain validator var anyError = false; $step.find("input").each(function () { if (!validator.element(this)) { // validate every input element inside this step anyError = true; } }); – Jay Nov 21 '16 at 12:21
  • I have this validator as the page is broken up for a wizard but it keeps giving error message even when checked – Jay Nov 21 '16 at 12:21
  • @Jay, I think you're on the right track if you remove, as Stephen mentioned, the RangeAttribute. It looks a little weird. If you don't want to go the custom ValidationAttribute route (MVC validation is definitely a pain point for beginners), I'd recommend making this input field `required` and maybe account for the special validation case in Javascript before the form is submitted. – alex Nov 21 '16 at 19:13

0 Answers0