Inline Validation On Blur
ReactJS
Medium
7 views
Problem Description
Validate a field only after it was touched (on blur).
Output Format
Render a React component.
Constraints
Track touched state and show error only when touched.
Official Solution
import React, { useState } from 'react';
export default function App() {
const [name, setName] = useState('');
const [touched, setTouched] = useState(false);
const error = touched && name.trim().length < 2 ? 'Enter at least 2 characters' : '';
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode blur validation</h2>
<label style={{ fontWeight: 700 }}>Name</label>
<input value={name} onChange={(e) => setName(e.target.value)} onBlur={() => setTouched(true)} style={{ marginTop: 6, width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid ' + (error ? '#c1121f' : '#bbb') }} />
{error ? <div style={{ marginTop: 8, color: '#c1121f' }}>{error}</div> : <div style={{ marginTop: 8, color: '#555' }}>Tip: click outside to validate.</div>}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!