I am trying to validate MVC 4 form with jquery, but I want to get data annotations attributes for do it.
My model:
[Required(AllowEmptyStrings = false,ErrorMessage = "Username is required")]
[Display(ResourceType = typeof(EntitiesResources), Name = "Username")]
string Username { get; set; }
[Display(ResourceType = typeof(EntitiesResources), Name = "Password")]
[Required(AllowEmptyStrings = false)]
string Password { get; set; }
[Display(ResourceType = typeof(EntitiesResources), Name = "Email")]
[DataType(DataType.EmailAddress)]
string Email { get; set; }
My MVC view:
<div class="row form-group">
<div class="col-xs-2 col-sd-2 col-md-2 col-lg-2">@Html.LabelFor(m => m.FirstName)</div>
<div class="col-xs-4 col-sd-4 col-md-4 col-lg-4">@Html.TextBoxFor(m => m.FirstName, new { required = "required" })</div>
<div class="col-xs-2 col-sd-2 col-md-2 col-lg-2">@Html.LabelFor(m => m.Email)</div>
<div class="col-xs-4 col-sd-4 col-md-4 col-lg-4">@Html.TextBoxFor(m => m.Email, new { required = "required" })</div>
My problem is that if I don´t put that 'required' attribute in MVC view, it doesn´t work ($("#UserForm").valid() returns always true). And I would like to use email validation too.
I call jquery validation on Ajax call:
$("#UserForm").validate();
if ($("#UserForm").valid()) {
var model = {
Id: $("#Id").val(),
FirstName: $("#FirstName").val(),
Email: $("#Email").val(),
LastName: $("#LastName").val(),
Enabled: $("#Enabled").val(),
Username: $("#Username").val(),
Password: $("#Password").val(),
}
$.ajax({
url: "SaveUser/Users",
type: "Post",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify(model),
success: function (data) {
alert(data.Message);
returnUsersGrid();
},
error: function (e) {
},
complete: function () {
}
});
}
Is there anyway to use data annotations with razor helpers and jquery validation, or data annotations only works with the server side validation with ModelState.isvalid()?
@Html.ValidationMessageFor(...)and include the relevant scripts (jquery.validate.jsandjquery.validate.unobtrusive.js) and removenew { required = "required" }(that is HTML5 client side validation only) - user3559349data: $('form').serialize(),and removecontentType: 'application/json',- user3559349if ($(this).valid()) {(not callingvalidate()) - user3559349[EmailAddress(ErrorMessage = "..")]on yourEmailproperty - user3559349