Hi I have created a function object that contains a set of properties.This is what I have:
function LoginModelDTO(data) {
var self = this;
self.UserName = ko.observable(data.UserName).extend({
minLength: {
params: 25,
message: "Username should have at least 25 chars"
},
required: {
message: "Username is required"
},
maxLength: {
params: 50,
message: "Username should not have more then 50 chars"
},
trackChanges: null
});
self.Password = ko.observable(data.Password).extend({
stringLength: {
params: 25,
},
required: {
message: "Password is required"
},
trackChanges: null
});
self.RememberMe = ko.observable(data.RememberMe).extend({
trackChanges: null
});
self.isValid = ko.computed(function () {
var bool = self.FirstName.isValid() &&
self.Username.isValid() &&
self.Password.isValid() &&
self.RememberMe() &&
return bool;
});
}
What I would like is to be able to find a way to iterate over each property and ask if it's valid without writing every property every time because I also have to write a similar structure like self.isValid for hasChanges , revertChanges etc.
Furthermore I will need to create other similar objects to LoginModelDTO that have around 30-35 properties.This will result in alot of code and a bigger javascript file then needed.
Is there any way I can iterate only threw the properties and check if they are valid? isValid should be skipped
eis gave you part of it in the comments, and Misters gave you a part in the answer, but here's it all together:
var allValidatablesAreValid = true;
for (var property in self)
{
if (self.hasOwnProperty(property) && self[property]["isValid"]) {
allValidatablesAreValid = allValidatablesAreValid && self[property].isValid();
}
// You can add an early bail out here:
// if (!allValidatablesAreValid) { break; }
}