Search code examples
knockout.jsdurandalknockout-validation

durandal with ko.validation.init


So, here is the problem i have been facing for couple of days.

I have a durandal application and i want to apply ko validation on the controls. Now, the validation does get applied but the problem is that it does not take affect at the first load. For e.g. if i have a text box which has required set as true and at the load time, this text box is empty, KO does not show required message.

It only shows message if i type something in the text box, then move out of the text box, come again in text box, remove the data and then again move out of the text box.

I even tried adding ko.validation.init({messagesOnModified: false}), and validation option in HTML inside div tag.

But no affect.

Below is my code

define(function (require) {
 ko.validation.init({
    messagesOnModified: false        
});
var duration = ko.observable().extend({
    required: { message: 'Please enter valid number.' }, number: true
});
var email = ko.observable().extend({ email: true, required: true });

var vm = {
    duration: duration,
    email: email

};
vm["errors"] = ko.validation.group(vm);
return vm;
});

HTML Code

            <span data-bind="text: errors().length"></span> Errors

            <div>
                <label for="txtDuration">Duration</label>
                <input name="txtDuration" type="text" data-bind="value: duration" />
                <span>(Min)</span>
            </div>
            <div>
                <label for="txtEmail">Email</label>
                <input name="txtEmail" type="text" data-bind="value: email" />
            </div>
            <input type="submit" value="Submit" data-bind="enable: isValid()">

    </form>

Please help.


Solution

  • This issue on the validation issue list describes the behavior: https://github.com/Knockout-Contrib/Knockout-Validation/issues/211.

    Proposed workarounds:

    Use vm.name.isModified(true) or vm.name.valueHasMutated() to trigger an update. http://jsfiddle.net/RainerAtSpirit/v6dek/6/

    ko.validation.init({
    
        messagesOnModified: false
    });
    
    var vm = {
        name: ko.observable().extend({
            required: true
        })
    };
    vm.name.isModified(true) // or alternatively vm.name.valueHasMutated();
    ko.applyBindings(vm);