Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You could seperate this into multiple files for more modularity */
- /* Using the getMatchCount helps to avoid multiple matches also being valid - Not typically necessary, just personal preference */
- const getMatchCount = (str, reg) => ((str || '').match(reg) || []).length;
- const name = (str) => getMatchCount(str, /^[A-Za-z ]{6,30}$/) === 1;
- const phoneNumber = (str) => getMatchCount(str, /^[0-9]{10}$/) === 1;
- const validateString = {
- name,
- phoneNumber,
- };
- /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
- const validate = (object, schema) => {
- const oKeys = Object.keys(object);
- const sKeys = Object.keys(schema);
- if(oKeys.length !== sKeys.length) return false;
- let result = true;
- for(let i = 0; i < sKeys.length; i++) {
- const sKey = sKeys[i];
- const oKey = oKeys[i];
- if(!schema[sKey](object[oKey])) {
- result = false;
- break;
- }
- }
- return result;
- };
- /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
- const info = {
- name: "John Doe",
- phone: "4792258422"
- };
- const schema = {
- name: validateString.name,
- phone: validateString.phoneNumber
- };
- const isValid = validate(info, schema);
- console.log(isValid);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement