寻找仅在输入字段部分完成时验证输入字段的解决方案,即不验证用户是否未输入值。 http://jsfiddle.net/2H2Bv/
还有兴趣看到一个解决方案,用于删除验证摘要消息,"在所有字段满足其验证要求时,在顶部填写缺少的字段,即当每个输入附加的所有验证消息都有在点击提交按钮之前消失...
HTML
<script id="customMessageTemplate" type="text/html">
<em class="customMessage" data-bind='validationMessage: field'></em>
</script>
<!-- ko if: displayAlert -->
<p class="customMessage" data-bind="text: validationSummary"></p> <br />
<!-- /ko -->
<fieldset>
<legend>Details</legend>
<label>First name:
<input data-bind='value: firstName' />
</label>
<label>Last name:
<input data-bind='value: lastName' />
</label>
<div data-bind='validationOptions: { messageTemplate: "customMessageTemplate" }'>
<label>Email:
<input data-bind='value: emailAddress' required pattern="@" />
</label>
</fieldset>
<br>
<button type="button" data-bind='click: submit'>Submit</button>
<br>
<br> <span data-bind='text: errors().length'></span> errors
JS:
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
decorateElement: true,
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
var viewModel = function() {
this.firstName = ko.observable().extend({
minLength: 2,
maxLength: 10
});
this.lastName = ko.observable().extend({
required: true
});
this.emailAddress = ko.observable().extend({ // custom message
required: {
message: 'Enter your email address.'
}
});
this.validationSummary = ko.observable("Complete missing fields below:");
this.displayAlert = ko.observable(false);
this.submit = function () {
if (this.errors().length == 0) {
alert('Thank you.');
} else {
this.displayAlert(true);
this.errors.showAllMessages();
}
};
this.errors = ko.validation.group(this);
};
ko.applyBindings(new viewModel());
答案 0 :(得分:0)
如果我理解正确,您希望在用户键入内容后运行电子邮件验证,而不是&#34; red&#34;当页面加载时。
要执行此操作,您需要删除required
和pattern
属性,以便您的输入成为:
<input data-bind='value: emailAddress' />
并向您的模型添加电子邮件验证,以便您的观察结果变为:
this.emailAddress = ko.observable().extend({ // custom message
required: {
message: 'Enter your email address.'
}, email:true
});
更新fiddle