将数据注释验证与 jquery 验证混合时,ASP.net MVC 验证失败

发布于 2024-11-10 02:19:57 字数 2288 浏览 5 评论 0原文

我有一个非常简单的示例,尝试在 MVC3 中使用数据注释和不显眼的 javascript:

模型:

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

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

控制器:

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

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

视图:

@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" />
}

一切正常。当我在表单为空时点击提交按钮时,它会阻止我提交。它输出不显眼的 JavaScript 并进行客户端验证。我想做一些远程验证以确保电子邮件地址未被使用,因此我将以下内容添加到视图中:

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

添加此内容后,我的验证将停止工作。我认为这是因为我将数据注释验证与 jquery 验证混合在一起。

如果我从模型中删除 [Required] 属性并将其添加到我的脚本中,那么一切都会正常:

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

一切正常。

我是否必须放弃不显眼的 javascript 验证才能使用此远程验证?有没有一种方法可以使用不显眼的 JavaScript 进行远程验证?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

格子衫的從容 2024-11-17 02:19:57

是的,问题源于这样一个事实:您将另一个验证处理程序附加到表单,该验证处理程序与 jquery 不引人注目的验证所附加的验证处理程序冲突。

要实现此目的,您可以使用 Remote 属性:

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

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

以及 HomeController 上的 CheckForValidEmail 操作:

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

现在您不再需要编写任何 JavaScript。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文