Knockout verification: how to check fields when a button is pressed, and not on changing input

I use the following knockout validation plugin: https://github.com/Knockout-Contrib/Knockout-Validation

I want to check my fields when I click the "Submit" button, and not every time I change the input value. How can i do this?

JavaScript:

ko.validation.init({ insertMessages:false, messagesOnModified:false, decorateElement: true, errorElementClass: 'wrong-field' }, true); var viewModel = { firstName: ko.observable().extend({minLength: 2, maxLength: 10}), lastName: ko.observable().extend({required: true}), age: ko.observable().extend({min: 1, max: 100}), submit: function() { if (viewModel.errors().length === 0) { alert('Thank you.'); } else { alert('Please check your submission.'); viewModel.errors.showAllMessages(); } }, }; viewModel.errors = ko.validation.group(viewModel); ko.applyBindings(viewModel); 

HTML:

 <fieldset> <div class="row" data-bind="validationElement: firstName"> <label>First name:</label> <input type="text" data-bind="textInput: firstName"/> </div> <div class="row" data-bind="validationElement: lastName"> <label>Last name:</label> <input data-bind="value: lastName"/> </div> <div class="row"> <div class="row"> <label>Age:</label> <input data-bind="value: age" required="required"/> </div> </div> </fieldset> <fieldset> <button type="button" data-bind='click: submit'>Submit</button> &nbsp; </fieldset> 

This is my jsfiddle: http://jsfiddle.net/xristo91/KHFn8/6464/

+6
source share
1 answer

Well, yes, validators quit when observables change. But ... you can trick using OnlyIf Option validators. I made a sample of Fiddler how it could work.

The question is more ... what do you want to do after the user clicks the first time ....

Basically, the sample sets the onlyIf condition for all validators and checks validateNow, decides when the validators should evaluate ... whatever ... in the submit method.

 self.validateNow = ko.observable(false); 

onlyIf gets the score on all validators:

 self.firstName = ko.observable().extend({ minLength: { message:"minlength", params: 2, onlyIf: function() { return self.validateNow(); } }, 

and validateNow is only set to submit

 self.submit = function() { self.validateNow(true); 

... I also increased the data binding a bit, because your sample only puts a red frame on the inputs.

I use to create my closures with constructors. So the sample is not the same "architecure" as yours, but I think you will pick it up.

+9
source

All Articles