在 React 中验证输入字段中的电子邮件
Validate an Email in an Input field in React
要在 React 中验证输入字段中的电子邮件,请使用test()
以下正则表达式 – 上的方法/\S+@\S+\.\S+/
。如果电子邮件有效,则该test
方法将返回,否则返回。true
false
import {useState} from 'react'; export default function App() { const [message, setMessage] = useState(''); const [error, setError] = useState(null); function isValidEmail(email) { return /\S+@\S+\.\S+/.test(email); } const handleChange = event => { if (!isValidEmail(event.target.value)) { setError('Email is invalid'); } else { setError(null); } setMessage(event.target.value); }; return ( <div> <input id="message" name="message" value={message} onChange={handleChange} /> {error && <h2 style={{color: 'red'}}>{error}</h2>} </div> ); }
我们onChange
在输入字段上设置了 prop,所以每次它的值改变时,handleChange
都会调用该函数。
在我们的handleChange
函数中,我们调用该isValidEmail
函数,将电子邮件传递给它。
The
Regexp.test
method returns true
if there is a match between the regular expression and the
string, otherwise false
is returned.
The forward slashes / /
mark the beginning and end of the regular expression.
function isValidEmail(email) { return /\S+@\S+\.\S+/.test(email); }
The \S
character matches a single character other than white space.
The +
character matches the preceding character one or more times.
.
, because dots have a special meaning in regular expressions.If you ever need help reading a regular expression, check this
regex cheatsheet
from MDN out.
Every time the value of the input field changes, we call the isValidEmail
method to check if the email is valid.
您也可以只执行一次 – 在您的提交处理程序函数中,但通常也可以在您的处理更改函数中执行此操作以向用户提供即时反馈。