Mikelon85
Mikelon85

Reputation: 432

How to use DataAnnotations attributes with jquery validation?

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

Upvotes: 0

Views: 5385

Answers (2)

Mikelon85
Mikelon85

Reputation: 432

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.

Upvotes: 0

Mohan Singh
Mohan Singh

Reputation: 1162

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>
  }

Upvotes: 1

Related Questions