<inputtype="text"name="zipcode"requiredpattern="[0-9]{5}"title="Five digit zip code"><inputtype="password"name="password"requiredminlength="8"maxlength="128"><inputtype="number"name="age"min="18"max="120">
Note Built-in validation runs on form submission and is bypassed by adding formnovalidate to the submit button or novalidate to the form. The title attribute provides a hint message shown when the pattern fails.
// Validate on change, blur, or submitconst errors ={};if(!value) errors.field='Required';
Example
functionSignupForm(){const[fields, setFields]=useState({ name:'', email:'', age:''});const[errors, setErrors]=useState({});const[touched, setTouched]=useState({});functionvalidate(data){const errs ={};if(!data.name.trim()) errs.name='Name is required';if(!data.email.includes('@')) errs.email='Invalid email';if(Number(data.age)<18) errs.age='Must be at least 18';return errs;}functionhandleChange(field, value){const updated ={...fields,[field]: value };setFields(updated);if(touched[field]){setErrors(validate(updated));}}functionhandleBlur(field){setTouched(prev =>({...prev,[field]:true}));setErrors(validate(fields));}functionhandleSubmit(e){
e.preventDefault();const errs =validate(fields);setErrors(errs);setTouched({ name:true, email:true, age:true});if(Object.keys(errs).length===0){submitSignup(fields);}}return(<form onSubmit={handleSubmit}><input
value={fields.name}
onChange={e =>handleChange('name', e.target.value)}
onBlur={()=>handleBlur('name')}/>{touched.name&& errors.name&&<span>{errors.name}</span>}{/* repeat for other fields */}<button type="submit">SignUp</button></form>);}
Note Validate on blur for a good UX: users see errors after leaving a field, not while typing. On submit, validate everything and mark all fields as touched. For complex forms, consider a form library or useReducer.
Frequently asked questions
How does HTML & CSS handle required field?
This task is covered in 2 stacks on this page: HTML & CSS, React. The "Form Validation Attributes" snippet in HTML & CSS uses `required | minlength="n" | maxlength="n" | pattern="regex" | min="n" | max="n"`.
Which code does the HTML & CSS example use?
The "Form Validation Attributes" snippet uses `required | minlength="n" | maxlength="n" | pattern="regex" | min="n" | max="n"`, from the Forms section of the HTML & CSS cheat sheet.
Which stacks cover "required field" on this page?
HTML & CSS, React. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Form Validation Attributes": Built-in validation runs on form submission and is bypassed by adding formnovalidate to the submit button or novalidate to the form. The title attribute provides a hint message shown when the pattern fails.