Skip to content

Instantly share code, notes, and snippets.

@pjchender
Last active July 13, 2017 14:04
Show Gist options
  • Save pjchender/ec18b023e255366003c7a427222fc210 to your computer and use it in GitHub Desktop.
Save pjchender/ec18b023e255366003c7a427222fc210 to your computer and use it in GitHub Desktop.
Snippet - Validation Object with Required
/**
* 利用 validate function 可以驗證 object 中的必填欄位有無填寫
**/
// object validation rules
const schema = {
firstName: {
required:true
},
lastName: {
required:true
}
}
// universal validation function
const validate = (schema, obj) => {
for(field in schema) {
if(schema[field].required) {
if(!obj[field]) {
return false;
}
}
}
return true;
}
let obj_valid = {
firstName: 'Aaron',
lastName: 'Chen'
}
let obj_invalid = {
firstName: 'Aaron',
}
console.log(validate(schema, obj_valid)) // true
console.log(validate(schema, obj_invalid)) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment