import React, { useState } from 'react'; function EmailInput() { const [email, setEmail] = useState(''); const [isValid, setIsValid] = useState(true); const validateEmail = (email) => { // Regular expression for email validation const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailPattern.test(email); }; const handleChange = (event) => { const inputValue = event.target.value; setEmail(inputValue); setIsValid(validateEmail(inputValue)); }; return ( <div> <label htmlFor="emailInput">Email:</label> <input type="text" id="emailInput" value={email} onChange={handleChange} style={{ borderColor: isValid ? 'initial' : 'red' }} /> {!isValid && <p style={{ color: 'red' }}>Please enter a valid email address.</p>} </div> ); } export default EmailInput;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter