在整个对象级别上运行验证而不是单个属性

时间:2014-02-03 15:13:14

标签: javascript validation knockout.js

我有一个简单的模型Employee如下:

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

在我看来,用户可以输入许多员工(默认情况下,我会显示10行输入10名员工)。现在我想验证我的数据(使用Knockout Validation):

  • 如果用户输入firstname的值,则lastname&&应验证email,但如果用户未输入firstname&&的任何值lastname&& email然后不需要运行验证。
  • 如果用户仅输入lastnameemail
  • 的值,也会应用同样的情况

简单来说,只有当对象的一个​​属性不为空时才运行验证,否则没有验证。任何建议?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你只想在只有一个属性没有价值但其他属性没有的时候激活验证。

以下是我的意思:

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