0

Updated to show a working sample with suggested changes which was changing my viewModel to be a validatedObservable per Thewads advice. Took quite a while to get things flowing but its now showing the correct error count!

<fieldset>
    <legend>Test</legend>
     <label>First name: <input data-bind='value: model.Employee.FirstName'/></label>
     <label>Last name: <input data-bind='value: model.Employee.LastName'/></label>
    <button type="button" data-bind='click: buttons.submit'>Submit</button>
</fieldset>


<script>

my = {namespace: { }}
my.namespace.obj = function () {
    var bindingHandler = function (data) {

        initializeValidation = (function () {
            ko.validation.configure({
                registerExtenders: true,
                decorateElement: true,
                messagesOnModified: true,
                insertMessages: true,
                parseInputAttributes: true,
                messageTemplate: null,
                grouping: { deep: true }
            });
        })();

         viewModel = ko.validatedObservable({
             model: ko.mapping.fromJS(data),
             buttons: {
                 submit: function () {
                     if (viewModel.isValid()) {
                         alert('VM clean');
                     } else {
                         alert('Errors found');
                         viewModel.errors.showAllMessages();
                     }
                 }
             }

        });

         extendedValidators = (function () {
             viewModel().model.Employee.FirstName.extend({ minLength: 20, required: true });
             viewModel().model.Employee.LastName.extend({ minLength: 30, required: true });
         })();

         applyBindings = (function () {
             ko.applyBindings(viewModel);
         })();
    }
    return {
        fn: {
            Initialize: function (model) {
                bindingHandler(model);
            }
        }
    };
};

$(document).ready(function () {
    model = { "Employee": { "FirstName": "Joe", "LastName": "Shmoe" } };
    my.namespace.obj().fn.Initialize(model);
});

james
  • 408
  • 7
  • 22

2 Answers2

2

You have to use a validatedObservable to properly validate, not just a normal observable.

Would be something like:

validationCheck = ko.validatedObservable( whatYouAreValidating() ) )
if (validationCheck.isValid() )
     //do your logic

Or by using validation groups:

validationGroupCheck = ko.validation.group( whatYouAreValidating())

if ( validationGroupCheck().length <= 0 )
    return true
Thewads
  • 4,953
  • 11
  • 55
  • 71
  • Just as a note, you could also look into using a ko.validation.group. It all depends on your needs. The validateObservable collects error messages but wraps the ViewModel in an observable, the validation.group just stores the validation messages. I can show this as an example if you need it – Thewads Jan 31 '13 at 15:19
  • Yeah could you please show me an example of the validation group? I'd like to be able to just check if my viewmodel is invalid, but do I need to have it as a validatedObservable to do that? – james Jan 31 '13 at 15:53
  • 1
    @cjsmith I've updated my answer to show validation.group. You can use either for just the sort of validation you are using I believe. By careful with validatedObservable if you are validating hundreds of observables at a time as performance will take a hit. Validation.groups is slightly quicker in these scenarios – Thewads Jan 31 '13 at 16:34
0

I can't get that to run at all. Can you get it running in a jsFiddle?

One thing that looks odd, however, is that there is nothing in your code calling your extendedValidators method, so I would guess that the validator just hasn't been initialised. Unless it's just missing from your post?

Paul Manzotti
  • 5,107
  • 21
  • 27
  • Actually, scrap jsFiddle, I'm struggling to get knockout validation to load in jsFiddle! – Paul Manzotti Jan 31 '13 at 09:19
  • the extendedValidators is self executing, doesn't need a direct call to it - to test you can throw an alert in there and it will fire – james Jan 31 '13 at 14:18
  • I did not know that, thanks! I can't see any mention of it in the documentation though, which was what I was going on. – Paul Manzotti Jan 31 '13 at 14:39
  • Oh yeah its name can be anything you want - its not in the documentation as its not particular to knockout validation, but javascript; Thats a function I added onto my viewmodel, the same as initialize – james Jan 31 '13 at 15:27
  • Ah right, gotcha, didn't notice that it was a self-calling function! – Paul Manzotti Jan 31 '13 at 15:36
  • Thanks for that, a really nice way of setting up the validation! – Paul Manzotti Jan 31 '13 at 19:53