0
votes

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()?

2
Just add @Html.ValidationMessageFor(...) and include the relevant scripts (jquery.validate.js and jquery.validate.unobtrusive.js) and remove new { required = "required" } (that is HTML5 client side validation only) - user3559349
And as a side note its just data: $('form').serialize(), and remove contentType: 'application/json', - user3559349
Have you included the scripts? And you should be handling the forms submit event (and cancelling it) an inside that script use if ($(this).valid()) { (not calling validate()) - user3559349
Also, did you enable client side validation? - Guruprasad J Rao
And for email validation you need to use [EmailAddress(ErrorMessage = "..")] on your Email property - user3559349

2 Answers

1
votes

Instead of using JQuery ajax to save data, try @Ajax.BeginForm ,It doesn't reload the entire page after submit ,It works same as jquery ajax call.

@using (Ajax.BeginForm("ActionMethodName", "ControllerName", new AjaxOptions{ HttpMethod = "POST"}, new { @enctype = "multipart/form-data" }))
{
    <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)
     @Html.ValidationMessageFor(model => model.FirstName)  </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)
    @Html.ValidationMessageFor(model => model.Email) </div>
    </div>
    <div class="row">
    <div class="col-md-12">
   <input type="submit" value="Save",class=" btn btn-primary"/>
  </div>
  </div>
  }
0
votes

Finally I have resolved the problem. I had validate and unobtrusive js referenced in my layout, I moved them to the form view and works fine. But this behavior makes me ask the next question. ¿Why $("#UserForm").valid() returns False and doesn´t fire javascript not declared Error?

Thanks guys.