Validate a Signup Body
Medium · Validation
Never trust req.body. Write validateSignup(body) that checks a signup request and returns { valid, errors }, where errors maps each bad field to ONE message (the first rule it breaks). valid is true when errors is empty.
- email (required): must match /^[^\s@]+@[^\s@]+\.[^\s@]+$/. Messages: "Email is required", "Email is invalid".
- password (required): at least 8 characters, then must contain a digit. Messages: "Password is required", "Password must be at least 8 characters", "Password must contain a number".
- age (optional): a whole number from 13 to 120 (the string "20" is not a number). Message: "Age must be a whole number from 13 to 120".
- name (optional): its trimmed length must be 1 to 50. Message: "Name must be 1-50 characters".
A required field is missing when it is undefined, null or "". Optional fields are only checked when they are not undefined/null. Assume email, password and name are strings when present.