问题
How do I stop the validation from firing when the page first loads? I want the validation to fire when the textbox gets edited or has focus and loses focus but not when the page first loads.
My Loading code:
$(document).ready(function () {
ko.validation.configure({
registerExtenders: true,
messagesOnModified: false,
decorateElement: true,
errorClass: 'error',
insertMessages: true,
parseInputAttributes: true,
messageTemplate: 'customMessageTemplate'
});
ko.applyBindings(new UserAccount(initdata), $("#UserAccount").get(0));
});
function UserAccount(data) {
var self = this;
self.UserName = ko.observable(data.UserName).extend({ required: { message: "Username is required" }, minlength: 6, maxLength: 12 });
self.Password = ko.observable(data.Password).extend({ required: { message: "Password is required" }, minlength: 6, maxLength: 12 });
self.Firstname = ko.observable(data.Firstname).extend({ required: { message: "Firstname is required" }, minlength: 6, maxLength: 40 });
...... other code .....
}
I have been trying to research this but nothing comes up that seems to work. I think there might be something in ko.validation.configuration 'messagesOnModified: false' (I tried true, and deleting that all together).
回答1:
You are on the right track: you need to set messagesOnModified: true otherwise the validation messages will be shown on load also.
However it is not working for you because you need to use the validationMessage binding in your messageTemplate otherwise it won't honor the messagesOnModified setting.
So you will need to change your template something like this:
<script type="text/html" id="customMessageTemplate">
<span data-bind="validationMessage: field"></span>
</script>
Demo JSFiddle.
来源:https://stackoverflow.com/questions/18969081/stop-knockoutjs-validation-during-applybindings-init-onload