Last active
July 13, 2017 14:04
-
-
Save pjchender/ec18b023e255366003c7a427222fc210 to your computer and use it in GitHub Desktop.
Snippet - Validation Object with Required
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 利用 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