Reputation: 2307
I want to show validation messages for my DOM elements for which the validation are written into Viewmodel:
My viewmodel code is as::
public class HotelDetailViewModel
{
public long DocumentHotelID { get; set; }
[Required(ErrorMessage = "Please enter Check In Date")]
public string CheckInDate { get; set; }
[Required(ErrorMessage = "Please enter Room Type")]
public string RoomType { get; set; }
[Required(ErrorMessage = "Please enter Nights")]
public int Nights { get; set; }
}
I have also used the Razor Validators as:
@Html.ValidationMessageFor(Model => Model.CheckInDate)
But I want to do the Validation on client side itself, without doing any submit. Because I have two forms on page and only one form can be submitted and for other I haveto do something using Jquery on client side, that I am asking. Thanks in Advance.
Upvotes: 0
Views: 93
Reputation: 7525
If you are allready using jquery.validate.min.js, you can add validation rules on client side.
<script src="jquery.validate.min.js" type="text/javascript"></script>
Example
@using (Html.BeginForm("action", "controller", new { Id = "ClientForm" }, FormMethod.Post))
{
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
<input type="submit" value="Log in" />
}
Add validation rules
<script>
$("#ClientForm").validate({
rules: {
'UserName': {
required: true,
maxlength: 20
}
},
messages: {
'UserName': {
required: 'Title required',
maxlength: 'Must be under 20 characters'
}
}
});
</script>
Upvotes: 0
Reputation: 1779
In MVC, to support DataAnnotation validation on client side, you just have to put this javascript file **jquery.unobtrusive-ajax.js, jquery.validate.min.js, jquery.validate.unobtrusive.min.js
which is can be render as
@Scripts.Render("~/bundles/jqueryval")
Upvotes: 0
Reputation: 909
To enable eager validation with the jQuery Validation plugin, use this code in your view
$('#myform').validate({
onfocusout: function(element) {
$(element).valid();
}
});
Upvotes: 1