Category: react
validate email or phone while typing in react
Published on 08 May 2026
Explanation
Validate email while typing using regex
and show error instantly if format
is invalid.
Code:
const emailRegex =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const handleEmail = (e) => {
const value = e.target.value;
if (!emailRegex.test(value)) {
setError('Invalid email');
} else {
setError('');
}
};
Explanation
Validate phone number while typing and
allow only numbers.
Code:
const handlePhone = (e) => {
const value = e.target.value;
if (/^\d*$/.test(value)) {
setPhone(value);
}
};
Explanation
Check phone length while typing and
show error if number is not
10 digits.
Code:
if (value.length !== 10) {
setError('Phone must be 10 digits');
} else {
setError('');
}
Explanation
Disable submit button until email or
phone becomes valid.
Code:
<button disabled={error || !email}>
Submit
</button>
Explanation
Show success message when email validation
passes successfully.
Code:
{!error && email && (
<p>Valid Email</p>
)}