Medium
How to Fix Form Validation That Doesn't Stop at First Error in JavaScript
Your team is building a form validation system that needs to check user input against multiple rules. The validation should stop at the first failure and return the error message. What's wrong with this implementation?
1const validators = {2 required: (value) => !value ? "This field is required" : null,3 minLength: (value, min) => value.length < min ? `Minimum length is ${min}` : null,4 email: (value) => !value.includes('@') ? "Invalid email format" : null,5 password: (value) => !/[A-Z]/.test(value) ? "Must contain uppercase letter" : null6};78function validateField(value, rules) {9 const errors = Object.entries(rules)10 .map(([rule, param]) => {11 if (validators[rule]) {12 return validators[rule](value, param);13 }14 return null;15 })16 .filter(Boolean);1718 return errors[0] || null;19}2021// Usage example:22const rules = {23 required: true,24 minLength: 8,25 password: true26};2728const result = validateField("password123", rules);