Knockout Validation viewmodel绑定未显示正确的错误

时间:2013-01-30 21:59:36

标签: knockout.js knockout-mapping-plugin knockout-validation

更新以显示包含建议更改的工作示例,该更改将我的viewModel更改为每个Thewads通知的validatedObservable。花了很长时间才能让事情顺利进行,但它现在显示正确的错误数!

<fieldset>
    <legend>Test</legend>
     <label>First name: <input data-bind='value: model.Employee.FirstName'/></label>
     <label>Last name: <input data-bind='value: model.Employee.LastName'/></label>
    <button type="button" data-bind='click: buttons.submit'>Submit</button>
</fieldset>


<script>

my = {namespace: { }}
my.namespace.obj = function () {
    var bindingHandler = function (data) {

        initializeValidation = (function () {
            ko.validation.configure({
                registerExtenders: true,
                decorateElement: true,
                messagesOnModified: true,
                insertMessages: true,
                parseInputAttributes: true,
                messageTemplate: null,
                grouping: { deep: true }
            });
        })();

         viewModel = ko.validatedObservable({
             model: ko.mapping.fromJS(data),
             buttons: {
                 submit: function () {
                     if (viewModel.isValid()) {
                         alert('VM clean');
                     } else {
                         alert('Errors found');
                         viewModel.errors.showAllMessages();
                     }
                 }
             }

        });

         extendedValidators = (function () {
             viewModel().model.Employee.FirstName.extend({ minLength: 20, required: true });
             viewModel().model.Employee.LastName.extend({ minLength: 30, required: true });
         })();

         applyBindings = (function () {
             ko.applyBindings(viewModel);
         })();
    }
    return {
        fn: {
            Initialize: function (model) {
                bindingHandler(model);
            }
        }
    };
};

$(document).ready(function () {
    model = { "Employee": { "FirstName": "Joe", "LastName": "Shmoe" } };
    my.namespace.obj().fn.Initialize(model);
});

2 个答案:

答案 0 :(得分:2)

您必须使用validatedObservable来正确验证,而不仅仅是正常的可观察对象。

会是这样的:

validationCheck = ko.validatedObservable( whatYouAreValidating() ) )
if (validationCheck.isValid() )
     //do your logic

或者使用验证组:

validationGroupCheck = ko.validation.group( whatYouAreValidating())

if ( validationGroupCheck().length <= 0 )
    return true

答案 1 :(得分:0)

我根本无法运行。你能在jsFiddle中运行吗?

然而,有一件事看起来很奇怪,你的代码中没有任何东西调用你的extendedValidators方法,所以我猜想验证器还没有被初始化。除非你的帖子中遗漏了它?