我正在使用敲除验证,当尝试检查isValid属性时,它始终为true。任何建议都很有用。
我的HTML标记
<div class="login">
<h1>
Customer login</h1>
<form action="/Home/login" method="post">
<div class="fontStyle">
<fieldset>
<legend></legend>
<div>
<label for="User-id">
User Id</label>
<input id="User-id" name="username" data-bind='value:UserName, valueUpdate: "afterkeydown"' type="text" value=""/>
<span data-bind='visible: UserName.hasError, text: UserName.validationMessage'> </span>
</div>
<div>
<label for="Password">
Password</label>
<input id="Password" name="password" data-bind='value:Password, valueUpdate: "afterkeydown"' type="password" value="" />
<span data-bind='visible: Password.hasError, text: Password.validationMessage'> </span>
</div>
<div>
<label>
</label>
<input type="submit" data-bind='click:submit' class="button" value="Login" />
</div>
</fieldset>
</div>
my javascript code block is
var loginModule = (function () {
$(document).ready(function () {
var userName = $('input:text[name=username]').val();
var password = $('input:text[name=password]').val();
ko.applyBindings(new viewmodel(userName, password));
});
ko.validation.registerExtenders();
var viewmodel = function (username, password) {
var that = this;
that.UserName = ko.observable(username).extend({ required: "User Id required", minLength: 5, maxLength: 10 });
that.Password = ko.observable(password).extend({ required: "Password required" });
that.valid = ko.validatedObservable(that);
that.submit = function () {
//trying to check user name is valid or not
alert(that.UserName.isValid());
};
};
return {
viewmodel: viewmodel
}
})();
当用户点击提交按钮时,我想通过检查isValid()方法进行验证。
答案 0 :(得分:3)
您需要使用任何验证ko.validation提供的扩展程序,在之前调用ko.validation.registerExtenders();
。
请在创建viewmodel
之前移动此行:
$(document).ready(function () {
var userName = $('input:text[name=username]').val();
var password = $('input:text[name=password]').val();
ko.validation.registerExtenders();
ko.applyBindings(new viewmodel(userName, password));
});
演示JSFiddle。
但是,如果您使用GitHub中的最新版验证插件,则无需再调用ko.validation.registerExtenders();
:Demo。