← All Exercises

Validate a Username with Custom Messages

intermediatejavascript~15min

Background

setCustomValidity accepts a single message, so applications must decide which ValidityState flag to report first.

Problem

Write validateField(state) for a username input that reports valueMissing, tooShort, tooLong, or patternMismatch in browser priority order and suppresses messages before first interaction.

Input

A JSON string with value, required, minLength, maxLength, pattern, and dirty fields.

Output

A JSON string with message and valid keys.

Sample tests

Sample 1

Input: {"value":"","required":true,"minLength":3,"maxLength":8,"pattern":"^[a-z]+$","dirty":true}
Expected: {"message":"Please enter a username.","valid":false}

Sample 2

Input: {"value":"ab","required":true,"minLength":3,"maxLength":8,"pattern":"^[a-z]+$","dirty":true}
Expected: {"message":"Use at least 3 characters.","valid":false}

Sample 3

Input: {"value":"Ada","required":true,"minLength":3,"maxLength":8,"pattern":"^[a-z]+$","dirty":true}
Expected: {"message":"Use lowercase letters only.","valid":false}

Sample 4

Input: {"value":"ada","required":true,"minLength":3,"maxLength":8,"pattern":"^[a-z]+$","dirty":true}
Expected: {"message":"","valid":true}

Sample 5

Input: {"value":"","required":true,"minLength":3,"maxLength":8,"pattern":"^[a-z]+$","dirty":false}
Expected: {"message":"","valid":false}

Your solution

Learning objective

Mirror ValidityState priority when producing custom messages and separate message visibility from actual validity.