nick gowdy
nick gowdy

Reputation: 6511

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

Upvotes: 5

Views: 6714

Answers (2)

S2K
S2K

Reputation: 1285

Give Some valid Name attribute to check boxes.Name of each Check Box Should Be same.Lets Say: Name="CheckBoxForItems"

On button Click event of Create Button:(In js)
Declare array and use each function to check if any check box is checked:

var arr = new Array();
$('input[name="CheckBoxForItems"]:checked').each(function (i) {
                arr.push($(this).attr("id"));
            });

 if(arr.length > 0)
$("#ButtonId").submit();
}

Upvotes: 0

dove
dove

Reputation: 20674

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 ;        
}

Upvotes: 10

Related Questions