I have a razor mvc 5 view where I want to validate some values.
The Model
public partial class PersonViewModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
The View
@using (Html.BeginForm("Process", "SomeController", FormMethod.Post, new { id = "processForm", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<!-- Buttons -->
<div class="row btn-row">
<div class="col-md-12">
<div class="pull-right">
<button class="btn btn-success"><span class="glyphicon glyphicon-floppy-save"></span> Save</button>
</div>
</div>
</div>
<!-- some more html -->
for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.CheckBoxFor(m => m[i].ToBeProcessed, new {@id = "[" + i + "[.ToBeProcessed"})
</td>
<td>
@Html.TextBoxFor(m => m[i].FirstName, new {@id = "[" + i + "].FirstName"})
@Html.ValidationMessageFor(m => m[i].FirstName, "Please enter a value", new {@class = "text-danger"})
</td>
<td>
@Html.TextBoxFor(m => m[i].LastName, new {@id = "[" + i + "].LastName"})
@Html.ValidationMessageFor(m => m[i].LastName, "Please enter a value", new {@class = "text-danger"})
</td>
</tr>
}
<!-- some more html -->
} <!-- form close -->
I only want to validate the rows where the checkbox [i].ToBeProcessed is checked. The text-boxes in the other rows should be ignored.
In my jQuery I have the following code:
@section Scripts {
@Script.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function(){
$("#processForm").validate({
rules: {"[0].FirstName": {required: "[0].ToBeProcessed:checked"},
{"[1].FirstName": {required: "[1].ToBeProcessed:checked"},
{"[0].LastName": {required: "[0].ToBeProcessed:checked"},
{"[1].LastName": {required: "[1].ToBeProcessed:checked"} // note that this is only fixed for testing purposes
});
});
</script>
}
Now, when running the code, check the first checkbox and hit the submit button, all textfields are validated instead of only the ones in the first row.
RequiredIfAttribute. It also has a client side validation.[RequiredIfTrue("ToBeProcessed")]or similar attribute applied to yourFirstNameandLastNameproperties - you get both client and server side validation