I have a model which has Required attributes in it. Is it possible to do data validation on a button click which is not of type submit. I did refer to this article and this one but it did not solve the issue.
Here's my model code.
[Required]
[Display(Name = "Number of beds")]
public int Beds { get; set; }
[Required]
[Display(Name = "Number of Inpatient Beds")]
public int InpatientBeds { get; set; }
My View
@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))
{
<div class="divPanel">
<div class="row">
<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">
@Html.LabelFor(m => m.InpatientBeds)
@Html.TextBoxFor(m => m.InpatientBeds, new { @class = "form-control", @type = "number"})
@Html.ValidationMessageFor(m => m.InpatientBeds)
</div>
<div class="col-md-3">
<button type=button class="btn btn-primary" id="btnCalculateScore" > Calculate Score</button>
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-primary" id="btnSaveChanges" data-toggle="modal"><i class="fa fa-share-square-o"></i> Update Status</button>
</div>
</div>
}
And my script
$('#btnCalculateScore').on('click', function (evt) {
evt.preventDefault();
if ($('#form1').valid()) {
//Do Something.
}
}
The validations do not work and the control enters the if loop even though the fields are empty? Is there something I am missing? Also does this approach also give out the validation messages which normally happen on a submit button event?
EDIT :
I added a normal Update Status button with type submit and the validations work there fine.
I added the id to my form to ensure it does not matter if the View contains another forms.
type="submit"? I just want to knowjquery.validate.unobtrusiveworks in your code.id="form1"- your overload ofBeginForm()is adding route values, not html attributes.