Advertisement
Guest User

Untitled

a guest
Aug 17th, 2023
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.25 KB | Software | 0 0
  1. /* You could seperate this into multiple files for more modularity */
  2.  
  3. /* Using the getMatchCount helps to avoid multiple matches also being valid - Not typically necessary, just personal preference */
  4.  
  5. const getMatchCount = (str, reg) => ((str || '').match(reg) || []).length;
  6.  
  7. const name = (str) => getMatchCount(str, /^[A-Za-z ]{6,30}$/) === 1;
  8. const phoneNumber = (str) => getMatchCount(str, /^[0-9]{10}$/) === 1;
  9.  
  10. const validateString = {
  11.   name,
  12.   phoneNumber,
  13. };
  14.  
  15. /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  16.  
  17. const validate = (object, schema) => {
  18.   const oKeys = Object.keys(object);
  19.   const sKeys = Object.keys(schema);
  20.  
  21.   if(oKeys.length !== sKeys.length) return false;
  22.  
  23.   let result = true;
  24.   for(let i = 0; i < sKeys.length; i++) {
  25.     const sKey = sKeys[i];
  26.     const oKey = oKeys[i];
  27.     if(!schema[sKey](object[oKey])) {
  28.       result = false;
  29.       break;
  30.     }
  31.   }
  32.   return result;
  33. };
  34.  
  35. /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  36.  
  37. const info = {
  38.   name: "John Doe",
  39.   phone: "4792258422"
  40. };
  41.  
  42. const schema = {
  43.   name: validateString.name,
  44.   phone: validateString.phoneNumber
  45. };
  46.  
  47. const isValid = validate(info, schema);
  48.  
  49. console.log(isValid);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement