Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I had a similar problem a while back and this is how I solved it: </p> <p><strong>Add a custom extender</strong></p> <pre><code>ko.extenders.spaceNotAllowed = function(target, options){ target.hasError = ko.observable(); target.validationMessage = ko.observable(); var validate = function(newValue) { // Validation for a field that shouldnt contain spaces if(value.indexOf(" ") === -1) target.hasError(false); else { target.hasError(true); target.validationMessage(target.hasError() ? options.errorMessage || "No spaces allowed" : ""); } } validate(target()); target.subscribe(validate); return target; } </code></pre> <p>In the ViewModel:</p> <p><strong>Use the extender in my view model on fields that need the validation</strong></p> <pre><code>var ViewModel = { var self = this; self.noSpaces = ko.observable('initialValue').extend({spaceNotAllowed: {errorMessage: 'no spaces allowed'}}); } </code></pre> <p><strong>Option 1</strong> Now, if you have a submit button on your html page, you can data-bind it like this:</p> <pre><code>&lt;button type='button' data-bind='click: saveStuff, enable: !noSpaces.hasError'&gt;Save&lt;/button&gt; </code></pre> <p>This way, the 'save button' will only be enabled if the validation passes. I found this answer a while back when I had the same problem and when I was fairly new to knockout. </p> <p><strong>Option 2</strong> CHeck if the fields are valid before AJAX:</p> <pre><code>if(self.noSpaces.hasError) { // Do something here return; } $.ajax(....); </code></pre> <p>This link explains how to use custom extenders in knockout: <a href="http://knockoutjs.com/documentation/extenders.html" rel="nofollow">Using extenders to augment observables</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload