I am working on KnockOut validation and so far so good. I do have a question though. I have some code like the following:
shippingMethodModel.Description.extend({ required: true });
And that shows a validation message below BUT does it set a flag or something which I can read to disable my save button?
I had this same need recently, so I’ll try to translate what I did based on the line of code you provided above…
Try adding a ko.computed observable similar to the following:
UPDATE
I made a correction in the code above after noticing my error.
For those declaring such a model/class as a function all at once, this code may look similar to the following:
/UPDATE
UPDATE2
Based on input from @ericb in the comments below, I made a change to the way I’m implementing my own solution, which I’ll demonstrate by adapting the example code in my update above:
Notice that I’ve now defined
formIsNotValidas an observable, but I’m using thevalidateObservableFormFieldfunction to help me with pre-submit form validity determination. This change ensures that theko.validation.groupfunction is called only as needed, and that call should only be needed when the observable being validated is valid, butformIsNotValidis true (to handle the case where that current observable was the one that had setformIsNotValidto true).Here’s an example of how I’m doing this:
goofy formatting to eliminate horizontal scroll
NOTE: I was already using this technique, but I’ve adapted it to improve the performance of checking whether or not the form is valid. @Californicated, I realized after my last comment that calling this function from the blur event of validated form fields is why I was seeing my save/submit button toggle between enabled and disabled states.
Thanks again to @ericb for the performance tip.
Further tips, from anyone, are always welcome!
/UPDATE2
Once you’ve got that in place, disabling the button is a matter of binding to that
formIsNotValidcomputed observable in whatever way makes sense for how you intend to disable the button, e.g.css: { 'ui-state-disabled': formIsNotValid }and/ordisable: formIsNotValidand/or some other method(s).Hope this helps, and let me know if you run into trouble.