Knockout validation message based set in the valid

2019-07-18 07:02发布

问题:

I want to set the message to display in the validation function of knockout similar to whats going on here: Knockout Validation Plugin Custom Error Message but without async.

Heres what ive tried, but no validation message is displayed.

this.name = ko.observable().extend({
    validation: {
        validator: function (val) {
            return { isValid:val === 'a', message: 'the value ' + val + ' is not a' };
        },
        message: 'I dont want this default message'
    }
});

JSFiddle

is there a good way to do this?

回答1:

close, the validator should be returning true/false if the rule passed. I couldn't get the message: to display the value (even setting is as a function had undefined arguments) so you can always inline the error message if you want to display the value back to the user.

this.name = ko.observable().extend({
    validation: {
        validator: function (val) {
            if (val !== 'a') {
                this.message = 'the value ' + val + ' is not a';
                return false;
            }
            return true;
        }
    }
});

http://jsfiddle.net/gEwEX/10/