Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Razor - at least one checkbox checked validation

I am new to mvc3 and razor engine and I would like it so at least one checkbox is checked for the submit button to fire.

 <div class="editor-field">
      @Html.Label("item1")
      @Html.CheckBoxFor(Model => Model.item1)
      @Html.Label("item2")
      @Html.CheckBoxFor(Model => Model.item2)
      @Html.Label("item3")
      @Html.CheckBoxFor(Model => Model.item3)
 </div>
 <p>
     <input type="submit" value="Create" />
 </p>

I know that I would need some kind of label to render text if 0 checkboxes are selected and that each checkbox needs an id so I can look at their values but is there anything in mvc3 razor to make this simpler? Thanks

like image 869
nick gowdy Avatar asked Nov 05 '12 10:11

nick gowdy


1 Answers

One way of many would be to

<input type="submit" value="Create" onclick="return submitWith();"/>
<span id="validationMessage" />

and in your javascript (you might have more here but keeping it simple)

function submitWith(){   
    var checkedCount = $("input:checked").length;
    var valid = checkedCount > 0;
    if(!valid){
         $('#validationMessage').html('You must select at least one option');
    }
    return valid ;        
}
like image 149
dove Avatar answered Oct 25 '22 02:10

dove