Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

validation - Javascript - elegant way to check object has required properties

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want "elegant", what you're looking for is called a schema:

var schema = {
  name: function (value) {
    return /^([A-Z][a-z-]* )+[A-Z][a-z-]*( w+.?)?$/.test(value);
  },
  age: function (value) {
    return !isNaN(value) && parseInt(value) == value && value >= 18;
  },
  phone: function (value) {
    return /^(+?d{1,2}-)?d{3}-d{3}-d{4}$/.test(value);
  }
};

var info = {
  name: "John Doe",
  age: "",
  phone: "123-456-7890"
};

function validate(object, schema) {
  var errors = Object.keys(schema).filter(function (key) {
    return !schema[key](object[key]);
  }).map(function (key) {
    return new Error(key + " is invalid.");
  });

  if (errors.length > 0) {
    errors.forEach(function (error) {
      console.log(error.message);
    });
  } else {
    console.log("info is valid");
  }
}

validate(info, schema);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...