ASP.NET MVC的jQuery的不显眼远程验证返回误报 [英] ASP.NET-MVC jQuery unobtrusive remote validation returns false positives

查看:88
本文介绍了ASP.NET MVC的jQuery的不显眼远程验证返回误报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我回来的一个项目,我去年在10个月前的工作,寻找一些code我们写了,希望现在有更好的方法来做到这一点...

I am back on a project I last worked on 9 months ago, looking at some code we wrote and hoping there is now a better way to do this...

虽然与jQuery的不显眼的审定pssed最初非常IM $ P $,我们最终不得不黑客下方放在一起(部分基于一个博客帖子我不能把我的手现在)来处理远程验证。问题在于,其中服务器端验证过程是缓慢的 - 通常任何涉及DB调用 - 验证程序将不会等待验证方法的响应,将作为虽然它已经传回了积极的

Though initially very impressed with jQuery's unobtrusive validation, we ended up having to put together the hack below (partly based on a blog post I can't put my hands on right now) to deal with remote validation. The problem being that where the server-side validation process was slow - typically anything involving a DB call - the validator would not wait for the response from the validation method and would act as though it had passed back a positive.

该黑客是基本保持检查是否验证器任何挂起的请求并没有进行,直到它有没有,当你可以确保一个真正的验证结果的:

The hack is to basically keep checking if the validator has any pending requests and not carry on until it has none, when you can be sure of a true validation result:

function SaveChangePassword() {

// Find form, fire validation
var $form = $("#btnSave").closest("form");

if ($form.valid()) {
//Do nothing - just firing validation
}

// Calls method every 30 milliseconds until remote validation is complete
var interval = setInterval(saveWhenValidationComplete, 30);

// Check if validation pending, save and clear interval if not
function saveWhenValidationComplete() {

    // Find form validator, check if validation pending - save once remote validation is finished
    var validator = $form.data("validator");
    if (validator.pendingRequest === 0) {

        clearInterval(interval);

        //Force validation to present to user (this will not retrigger remote validation)
        if ($form.valid()) {

            var closeButton = "<br/><input type='button' value='OK' style='font-size:small; font-weight:bold; float:right;' onclick=\"$('#changePasswordDialog').dialog('close');\" class='greenbutton' />";
            // If form is valid then submit
            $.ajax(
                {
                    type: "POST",
                    url: "/Account/SavePassword",
                    data: $form.serialize(),
                    success: function (result) {
                        var successMessage = "<div style='text-align:center; margin-top: 10px;'>" + result + "<div>";
                        $("#changePasswordDialog").html(successMessage + closeButton);
                            },
                    error: function (jqXhr, textStatus, errorThrown) {
                        // Populate dialog with error message and button
                        var errorMessage = "<div style='text-align:center'>Error '" + jqXhr.status + "' (Status: '" + textStatus + "', errorThrown: '" + errorThrown + "')<div>";
                        $("#changePasswordDialog").html(errorMessage + closeButton);
                    }
                });

        }

        // Else validation will show
    }

    // Else don't save yet, wait another 30 miliseconds while validation runs
};

// Prevent default and stop event propagation
return false;
}

我希望,在过去的9个月中,已经有一些进展,这不再是必要的!任何想法表示欢迎,让我知道如果我能提供任何进一步的细节。

I am hoping that in the last 9 months there have been some developments and this is no longer necessary! Any ideas welcome, let me know if i can provide any further detail.

推荐答案

虽然可以提供客户端验证始终提供一个准确到你的用户,你应该(永远!的)重验证服务器上。这真的很容易为用户禁用javascript或以其他方式伪造一个无效POST到控制器的动作,如果你不检查的东西服务器端你为用户创造腐败的数据在系统中的机会。

While you can provide client-side validation is provided as a nicety to your users, you should always (always!) re-validate on the server. It's really easy for users to disable javascript or otherwise fake an invalid POST to your controller action, and if you don't check things server-side you're creating an opportunity for users to corrupt the data in your system.

幸运的是,ASP.NET MVC最验证是pretty多为你做。如果您的控制器动作看起来是这样的:

Fortunately, most validation in ASP.NET MVC is pretty much done for you. If your controller action looks like this:

public ActionResult SaveSomething(Something thing)
{
    if(!ModelState.IsValid)
    {
        return View("EditSomething", thing);
    }
    // otherwise, save something...
}

...然后你会发现问题,用户提供的值不能结合到你的数据属性,以及由属性,如验证的事情[必需] [StringLength(X)] 。然而,一些形式的验证不会自动检查你。 [遥控] 是其中之一。

... then you're going to catch issues where users provided values that can't bind to your data properties, as well as the things validated by properties like [Required] and [StringLength(x)]. However, some forms of validation aren't automatically checked for you. [Remote] is one of these.

如果你有一个指向这样的控制器操作的 [遥控] 属性:

If you have a [Remote] attribute that points to a controller action like this:

public ActionResult CheckThingCodeValidity(string code)
{
    return Json(_thingCodeChecker.ThingCodeWorks(code), JsonRequestBehavior.AllowGet);
}

...那么你也应该有这样的事情在你提交的行动:

... then you should also have something like this in your submit action:

public ActionResult SaveSomething(Something thing)
{
    if(!_thingCodeChecker.ThingCodeWorks(thing.Code))
    {
        ModelState.AddModelError("Code", "This code is not valid.");
    }
    if(!ModelState.IsValid)
    {
        return View("EditSomething", thing);
    }
    // otherwise, save something...
}

这样,你的标准服务器端验证技术工程视图发回给用户,并让他们在该属性是一个错误消息,表示他们需要解决什么。

That way, your standard server-side validation technique works to send the view back to the user, and gives them an error message on that property to indicate what they need to fix.

如果你这样做,那么你不必担心当表单被提交异步验证检查是否仍在进行中。如果你的客户端验证失败一般,无论是通过一个缺陷,网络问题,或恶意用户干预也没关系。你仍然是$ P $从提交信息无效pventing他们,他们还是会得到一个很好的观点,告诉他们为什么他们提交无效。

If you are doing this, then you don't have to worry about whether an asynchronous validation check is still underway when the form gets submitted. And it doesn't matter if your client-side validation fails generally, either through a defect, a network issue, or malicious user intervention. You'll still be preventing them from submitting something invalid, and they'll still get a nice view telling them why their submission was invalid.

这篇关于ASP.NET MVC的jQuery的不显眼远程验证返回误报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆