Hackforge Academy

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>
)}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community