Medium
This question is a daily question and will count towards your daily streak.
In a data validation system, you need to validate user input against a set of rules. What will be the validation result for this input?
1class Validator {2 static rules = {3 number: (val) => typeof val === 'number' && !isNaN(val),4 string: (val) => typeof val === 'string' && val.length > 0,5 email: (val) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val),6 array: (val) => Array.isArray(val) && val.length > 07 };89 static validate(input, schema) {10 const results = Object.entries(schema).map(([field, rules]) => {11 const value = input[field];12 const errors = rules13 .filter(rule => !this.rules[rule](value))14 .map(rule => `Invalid ${rule}`);1516 return { field, valid: errors.length === 0, errors };17 });1819 return {20 valid: results.every(r => r.valid),21 fields: results22 };23 }24}2526const input = {27 age: "25",28 email: "[email protected]",29 tags: []30};3132const schema = {33 age: ['number'],34 email: ['string', 'email'],35 tags: ['array']36};3738console.log(Validator.validate(input, schema));