我有一个简单的JSFiddle示例http://jsfiddle.net/b625zeL5/6/
<script>
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: false,
parseInputAttributes: true,
messageTemplate: 'errorTemplate',
decorateInputElement: true,
errorElementClass: 'error'
}, true);
var ViewModel = function(){
this.email = ko.observable("")
.extend({ required: true })
.extend({ email: true });
this.password = ko.observable("")
.extend({ required: true });
};
var viewModel = new ViewModel();
viewModel.errors = ko.validation.group(viewModel);
ko.applyBindings(viewModel);
</script>
<form>
<span data-bind="validationMessage: email"></span>
<input type="text" id="email" data-bind="value: email, validationElement: email, valueUpdate:'keyup'" /> <br/>
<span data-bind="validationMessage: password"></span>
<input type="text" id="password" data-bind="value: password, validationElement: password, valueUpdate:'keyup'"/>
</form>
<script type="text/html" id="errorTemplate">
Error: <span data-bind="validationMessage: field">X</span>
</script>
如您所见 - 我禁用了insertMessages,因为我需要在输入字段之前显示错误消息。因此,我添加了&#34; data-bind =&#34; validationMessage:email&#34;&#34;在每个文本输入之前。
我在验证配置中定义 messageTemplate:&#39; errorTemplate&#39; 但错误消息仍然是纯文本。如何让messageTemplate工作?
答案 0 :(得分:0)
因为您关闭了insertMessages,所以敲除验证将不会使用您的错误消息模板,它将使用您在每个字段上方插入的内容。
您有两种选择:
示例1:
this.password = ko.observable("")
.extend({ required: {
params: true,
message: "Error: This is required"
}
});
示例2:
<script type="text/html" id="errorTemplate">
Error: <span data-bind="validationMessage: error_field"></span>
</script>
..在表单内部,您可以调用模板,如:
<form>
<!-- ko template: { name: 'errorTemplate', data: { error_field: email } }-->
<!-- /ko -->
<input type="text" id="email" data-bind="value: email, validationElement: email, valueUpdate:'keyup'" /> <br/>
...
...
请参阅jsfiddle,其中示例2在行动中:http://jsfiddle.net/mhgv48e8/
希望有所帮助:)