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?