Dismissile
Dismissile

Reputation: 33071

ASP.net MVC Validation fails when mixing dataannotations validation with jquery validation

I have an extremely simple example trying to use Data Annotations with unobtrusive javascript in MVC3:

Model:

public class RegisterModel {
    [Required]
    public string EmailAddress { get; set; }

    [Required]
    public string FirstName { get; set; }
}

Controller:

public class HomeController : Controller {
    public ActionResult Index() {
        return View(new RegisterModel());
    }

    [HttpPost]
    public ActionResult Index(RegisterModel model) {
        return View(model);
    }
}

View:

@model RegisterModel

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using( Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "mainForm" } ) ) {
    @Html.EditorFor( m => m.FirstName)<br/>
    @Html.ValidationMessageFor( m => m.FirstName)<br/>

    @Html.EditorFor(m => m.EmailAddress)<br/>
    @Html.ValidationMessageFor(m => m.EmailAddress)<br/>

    <input type="submit" value="Submit" />
}

Everything works fine. When I hit the submit button while the form is empty it prevents me from submitting. It outputs unobtrusive javascript and does client validation. I wanted to do some remote validation to make sure the email address is not in use so I added the following to the view:

<script type="text/javascript">
    $("#mainForm").validate({
        rules: {
            EmailAddress: {
                email: true,
                remote: {
                    url: "@Url.Action("CheckForValidEmail")",
                    type: "post"
                }
            }
        },
        messages: {                
            EmailAddress: { 
                email: "You must provide a valid e-mail address.",
                remote: jQuery.format("The email {0} is already in use.")
            }
        }
    });
</script>

As soon as I add this my validation stops working. I think it is because I'm mixing the data annotations validation with the jquery validation.

If I remove the [Required] attributes from the model and add this to my script then everything works:

FirstName: { required: true },
EmailAddress: { required: true, email: true, remote ... }

Everything works fine.

Do I have to give up unobtrusive javascript validation to use this remote validation? Is there a way to do remote validation with unobtrusive javascript?

Upvotes: 1

Views: 1423

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Yes the problem comes from the fact that you are attaching another validate handler to the form which conflicts with the one attached by the jquery unobtrusive validation.

To achieve this you could use the Remote attribute:

public class RegisterModel {
    [Required]
    [Remote("CheckForValidEmail", "Home")]
    public string EmailAddress { get; set; }

    [Required]
    public string FirstName { get; set; }
}

and the CheckForValidEmail action on HomeController:

public ActionResult CheckForValidEmail(string emailAddress)
{
    if (repository.IsValid(emailAddress))
    {
        // If you return a JSON string the model will be considered
        // invalid and this string will be used as error message
        return Json(
            string.Format(
                "The email {0} is already in use.", 
                emailAddress
            ), 
            JsonRequestBehavior.AllowGet
        );
    }
    // Return true to indicate that the email address is valid
    return Json(true, JsonRequestBehavior.AllowGet);
}

Now you no longer need to write any javascript.

Upvotes: 2

Related Questions