ebram khalil
ebram khalil

Reputation: 8331

run validation on whole object level not individual properties

I have a simple model Employee as following:

Employee = function(empId, fName, lName, empEmail, empPermission) {
    this.firstname = ko.observable(fName);
    this.lastname = ko.observable(lName);
    this.email = ko.observable(empEmail);
}

In my view user can enter many employees(by default i show 10 rows to enter 10 employees). Now i want to validate my data as(using Knockout Validation):

In simple words run validation only if one property of the object is not empty, otherwise no validation .. Any Suggestion?

Upvotes: 1

Views: 65

Answers (1)

Ali Habibzadeh
Ali Habibzadeh

Reputation: 11568

If I understand correctly you only want to fire validation when there is only one property that has no value but the rest do.

Here is how I would go about it:

ko.validation.configure({
    messagesOnModified: true,
    insertMessages: true
});

// Utility function to count how many times something appears in an array
function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    return count;
}

var Employee = function(empId, fName, lName, empEmail, empPermission) {
    var self = this;
    self.isThereSingleEmptyProp = function(){
        var props = [];
        // keep array of these 3 items we care about
        ko.utils.objectForEach(self, function(item){
            if (item === "firstname" || item ==="lastname" || item ==="email"){
                props.push(self[item]());
            }
        });
        // Returns true if only a single element does not have a value
        return countInArray(props, "") === 1;
    }
    self.firstname = ko.observable(fName || "").extend({
        required: {
            message: "Please fill all fields",
            // Checks if a property with no value is singled out
            onlyIf: self.isThereSingleEmptyProp
        }
    });
    self.lastname = ko.observable(lName || "").extend({
        required: {
            message: "Please fill all fields",
            // Checks if a property with no value is singled out
            onlyIf: self.isThereSingleEmptyProp
        }
    });
    self.email = ko.observable(empEmail || "").extend({
        required: {
            message: "Please fill all fields",
            // Checks if a property with no value is singled out
            onlyIf: self.isThereSingleEmptyProp
        }
    });
    self.errors = ko.validation.group(self);
}


ko.applyBindings(new Employee());

Here is a working fiddle

Upvotes: 1

Related Questions