In cases where you need to ensure model validation using Jquery, .valid() function can be used.
The model class fields
[Required]
[Display(Name = "Number of Hospitals")]
public int Hospitals{ get; set; }
[Required]
[Display(Name = "Number of Beds")]
public int Beds { get; set; }
The View code
@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))
{
<div class="divPanel">
<div class="row">
<div class="col-md-3">
@Html.LabelFor(m => m.Hospitals)
@Html.TextBoxFor(m => m.Hospitals, new { @class = "form-control", @type = "number"})
@Html.ValidationMessageFor(m => m.Hospitals)
</div>
<div class="col-md-3">
@Html.LabelFor(m => m.Beds)
@Html.TextBoxFor(m => m.Beds, new { @class = "form-control", @type = "number"})
@Html.ValidationMessageFor(m => m.Beds)
</div>
<div class="col-md-3">
<button type=button class="btn btn-primary" id="btnCalculateBeds"> Calculate Score</button>
</div>
</div>
</div>
}
The script for Validation check.
$('#btnCalculateBeds').on('click', function (evt) {
evt.preventDefault();
if ($('#form1').valid()) {
//Do Something.
}
}
Ensure that the jquery.validate
and jquery.validate.unobtrusive
files are present in the solution.