KO验证组错误

时间:2014-07-07 11:53:26

标签: validation knockout.js knockout-validation

我使用简单的登录页面来捕获登录名和密码。当用户点击忘记密码按钮时,我只验证登录文本框。

它在初始页面加载时运行良好。最初如果我保持用户ID为空并单击忘记密码触发验证错误,如果我更正,我仍然在错误对象中获取空值。我不确定这个空值来自何处。

我的代码关注

Javascript

var loginModule = (function () {
$(document).ready(function () {

     var userName = $('input:text[name=username]').val();
     var password = $('input:text[name=password]').val();

     ko.validation.registerExtenders();
     ko.validation.init();
     ko.applyBindings(new viewmodel(userName, password));

});



var viewmodel = function (username, password) {

    var self = this;

    self.UserName = ko.observable(username).extend({ required: { message: 'User Id is required.' }, minLength: 5, maxLength: 10 });

    self.Password = ko.observable(password).extend({ required: { message: 'Password is required.' }, minLength: 5, maxLength: 10 });

     self.forgotPassword = function () {

        var fperrors = ko.validation.group(self.UserName, { deep: false});

         if (fperrors().length > 0) {

            $('#errorMsg').show();

            fperrors.showAllMessages();

        }

        else {

            //valid code

        }

     };
};

 return {
    viewmodel: viewmodel

}

})();

如果我改变了       var fperrors = ko.validation.group(self.UserName,{deep:false});

要       var fperrors = ko.validation.group(self.UserName(),{deep:false});

根本没有抛出验证错误。

Html标记

<P>

<p>

<span class="error" data-bind='visible: UserName.hasError, text: UserName.validationMessage'></span>

</p>

<LABEL class="field-label" for="User-id">User ID / alias<EM class=mandatory>*</EM></LABEL><input id="User-id" name="username" class=field-stretch data-bind='value:UserName, valueUpdate: "afterkeydown"'

                        type="text" value="" /></P>

<P>

<p><span class="error" data-bind='visible: Password.hasError, text: Password.validationMessage'></span></p>

<LABEL class=field-label for=Password>Password<EM class=mandatory>*</EM></LABEL>   <input id="Password" name="password" class=field-stretch data-bind='value:Password, valueUpdate: "afterkeydown"' type="password" value="" /></P>

<P class="text-left btn-wrap"><INPUT class="btn-primary" data-bind='click:submit'  value="Logon" type=submit> &nbsp; <INPUT data-bind='click:forgotPassword' class=btn-primary value="Forgotten password?" type=submit>  </P>

有人可以帮助解决它的错误吗?

1 个答案:

答案 0 :(得分:1)

我不确定为什么但是在我的测试中我必须将observable作为数组传递才能使它工作:

var fperrors = ko.validation.group([self.UserName], { deep: false});

http://jsfiddle.net/LHy6h/