gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
i want to validate input in react with regex,can you write me a sample code
- User
i want to validate input in react with regex,can you write me a sample code
- Assistant
Sure, here is a sample code for validating an email input field using regular expressions in React:
import React, { useState } from "react"; function App() { const [email, setEmail] = useState(""); const [emailError, setEmailError] = useState(""); const validateEmail = (e) => { const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; const inputEmail = e.target.value; setEmail(inputEmail); if (!emailRegex.test(inputEmail)) { setEmailError("Enter a valid email address"); } else { setEmailError(""); } }; return ( <div> <label>Email:</label> <input type="email" value={email} onChange={validateEmail} /> {emailError && <p>{emailError}</p>} </div> ); } export default App;In the above code, we define a
validateEmail()function that uses a regular expression to match the input email. We then call this function on theonChange()event of ainputtag, which updates ouremailstate with the current value of the input field. If the input email does not match the regular expression, we set an error message in theemailErrorstate variable usingsetEmailError(). Finally, we display the error message using conditional rendering in the JSX code.