淘汰赛 + Jquery 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5734851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:44:05  来源:igfitidea点击:

Knockout + Jquery Validate

jqueryjquery-validateknockout.js

提问by RubbleFord

I'm trying to setup validation with jquery validate, and i've got the viewmodel coming back from the server, mapped to the client and successfully have knockout js binding some data.

我正在尝试使用 jquery validate 设置验证,并且我已经从服务器返回了视图模型,映射到客户端并成功地将淘汰赛 js 绑定了一些数据。

I included a called to validate but the validation never triggers, however if I put a class on the input box and then call valid it triggers as expected.

我包含了一个调用来验证但验证永远不会触发,但是如果我在输入框中放置一个类然后调用valid它会按预期触发。

Any ideas?

有任何想法吗?

<script type="text/javascript">
        var viewModel;
        $(document).ready(function () {
            $.ajax({
                url: 'Home/GetUserData',
                type: 'post',
                success: function (data) {
                    viewModel = ko.mapping.fromJS(data);
                    viewModel.save = function () { sendToServer(); };
                    ko.applyBindings(viewModel);
                    main();
                }
            });
        });

        function main() {
            $("form").validate({
                rules: {
                    birthPlace: {
                        required: true,
                        minlength: 2
                    }
                }
            });
        }

        function sendToServer() {
            alert($("form").valid());
        }

    </script>
}
<h2>@ViewBag.Message</h2>
<form id="nameSubmit" action="">
    <div>
        The name is: <span id="test" data-bind="text: Name"></span>
    </div>
    <div>
        He's <span id="age" data-bind="text: Age"></span>
    </div>
    <div>
        He's from
        <input type="text" id="birthPlace" name="birthPlace"/>
    </div>
    <div>
        <button data-bind="click: save">Click Me</button>
    </div>
</form>

回答by Ryley

By default jQuery Validate does it's validation on submit. So if knockout is interrupting that, i.e. by not actually triggering the onSubmitevent, that would do it. Your best bet may be to do as you were somewhat planning there in your sendToServer function - manually trigger the validation from your knockout submit event:

默认情况下,jQuery Validate 在提交时进行验证。因此,如果淘汰赛打断了这一点,即实际上没有触发onSubmit事件,那就可以了。您最好的选择可能是按照您在 sendToServer 函数中的计划进行操作 - 从您的淘汰赛提交事件手动触发验证:

if (!$('form').valid()){
    $('form').showErrors();
    return false;
}

//otherwise, get on with whatever knockout needs to do
...
return true;

回答by Richard

There is now a knockout jQuery validate binding, which I find very useful:

现在有一个淘汰赛 jQuery 验证绑定,我觉得它非常有用:

https://github.com/Knockout-Contrib/Knockout-Validation

https://github.com/Knockout-Contrib/Knockout-Validation

回答by Gudlaugur Egilsson

I'd like to recommend against using jQuery validate with knockout. The reason is that jQuery validate binds to the DOM, while knockout recommends working with the view model. This will lead to problems once you start adding more dependencies on the validation, such as preventing certain behavior if data is invalid, but you still need to retain the data. Go for knockout validation, it does the job very well.

我想建议不要使用带有淘汰赛的 jQuery 验证。原因是 jQuery 验证绑定到 DOM,而淘汰赛建议使用视图模型。一旦开始在验证上添加更多依赖项,这将导致问题,例如在数据无效时阻止某些行为,但您仍然需要保留数据。进行淘汰赛验证,它可以很好地完成工作。

回答by craigb

I've been using the submitHandler option on validate():

我一直在使用 validate() 上的 submitHandler 选项:

$("#myform").validate({
 submitHandler: function(form) {
   viewModel.sendToServer()
 }
});

On the form, just use a standard <input type="submit">and jQuery validation will pick up the event, validate, and if valid will call your handler on the viewModel.

在表单上,​​只需使用标准<input type="submit">和 jQuery 验证将获取事件,验证,如果有效将调用您在 viewModel 上的处理程序。

回答by MikeBeaton

It is correct that jQuery Validation only does its validation on the form submit event (as per Ryley's answer). So ifyou use Knockout style data-bind="click:modelSubmit"this will prevent the form submit from firing (by default) and so prevent jQuery Validation from doing anything.

jQuery Validation 仅对表单提交事件进行验证是正确的(根据 Ryley 的回答)。因此,如果您使用 Knockout 样式,data-bind="click:modelSubmit"这将阻止提交表单(默认情况下),从而阻止 jQuery 验证执行任何操作。

You have two options. The first is to return truefrom modelSubmit(), which will make Knockout fire the form submit (but only aftermodelSubmithas finished) (http://knockoutjs.com/documentation/click-binding.html).

你有两个选择。首先是返回truemodelSubmit(),这将使得火淘汰赛的形式提交(但只有modelSubmit已完成)(http://knockoutjs.com/documentation/click-binding.html)。

The second - and most likely what you want - is to leave off data-bind="click"altogether and use a jQuery Validation submit handler instead (https://jqueryvalidation.org/validate).

第二个 - 也很可能是您想要的 - 是data-bind="click"完全放弃并使用 jQuery 验证提交处理程序(https://jqueryvalidation.org/validate)。

$("#myform").validate({
    submitHandler: function(form) {
        viewModel.modelSubmit();
    }
});

This handler only gets called once the validation has succeeded.

只有在验证成功后才会调用此处理程序。