0
votes

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);
});

2

2 Answers

2
votes

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
0
votes

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?