I'm looking for an good / elegant way to validate that a javascript object has the required properties, so far this is what I have:
var fields = ['name','age','address'];
var info = {
name: "John Doe",
age: "",
phone: "123-456-7890"
}
var validateFields = function(o, required_fields) {
required_fields.forEach(function(field){
if(o.hasOwnProperty(field)){
if(o[field]){
console.log(field + ": " + o[field]);
}else{
console.log(field + " exists but is empty");
}
}else{
console.log(field + " doesn't exist in object");
}
});
}
validateFields(info, fields);
Is there a more efficient / elegant way of doing this in plain javascript?
EDIT: Ok so I'm glad I asked because I had completely missed a bunch of possible conditions like zero.
With elegance out the window, how is this for a validation function? Are there any other cases I should be checking for?
var fields = ['name','age','address'];
var info = {
name: "John Doe",
age: 0,
address: false,
phone: "123-456-7890"
}
var validateFields = function(o, required_fields, null_valid, zero_valid, empty_valid) {
var invalid_fields = [];
required_fields.forEach(function(field){
if(field in o){
switch(o[field]){
case '':
console.log(field + " exists but is empty");
if(!empty_valid){
invalid_fields.push(o[field]);
}
break;
case undefined:
console.log(field + " exists but is undefined");
invalid_fields.push(o[field]);
break;
case null:
console.log(field + " exists but is null");
if(!null_valid){
invalid_fields.push(o[field]);
}
break;
case 0:
console.log(field + " exists and the value is 0");
if(!zero_valid){
}
invalid_fields.push(o[field]);
break;
default:
console.log(field + ": " + o[field]);
break;
}
}else{
console.log(field + " doesn't exist in object");
invalid_fields.push(o[field]);
}
});
return invalid_fields;
}
var invalid = validateFields(info, fields, true, true, false);
console.log(invalid);
if(invalid.length >0){
console.log("ERROR: Missing fields");
}else{
console.log("Fields are valid");
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…