Search code examples
javascriptknockout.jsknockout-validation

Knockout minLength with empty string allowed


I am new to knockout, and trying to workout how to use validations. We have the following piece of code -

    var MyObjectModel = function(myObject){
    var self = this;
    self.myNumber = ko.observable(myObject.number).trimmed();
    self.myNumber.extend({
        minLength: {
            params: 7,
            message: "My Number is too short."
        },
        maxLength: {
            params: 7,
            message: "My Number is too long."
        }
    });

    self.errors = ko.validation.group(self);
}

Now I would like to change the code so that either the length of myObject.number should be either exactly 7, or the field should be empty. How do I go about making this change ?

Any help would be appreciated. In case you think something is not clear, please let me know so I can elaborate more.


Solution

  • You can use a custom pattern to it:

    var MyObjectModel = function(myObject){
        var self = this;
        self.myNumber = ko.observable(myObject.number).trimmed();
        self.myNumber.extend({
            pattern: {
                params: '^[0-9]{7}$|^$',
                message: "My Number must have 7 chars or stay empty."
            }
        });
    
        self.errors = ko.validation.group(self);
    }