如果用户输入的输入不是使用 javascript 的有效电子邮件并做出反应,如何禁用按钮?

我想将电子邮件验证添加到输入字段,如果用户输入的电子邮件错误,则基于此禁用添加按钮。


下面你可以看到我的代码,


function Parent() {

    const [email, setEmail] = useState('');

    const onEmailChange = (event: any) => {

        setEmail(event.target.value);

    };


   const isDisabled = email.length === 0;


    return (

         <Input

             type="email"

             value={email}

             onChange={onEmailChange}

             placeholder="Insert user email"

         />

         <button disabled={isdisabled}>Add</button> //add button to be disabled when      user input email is wrong

   );

}


我想确保我对输入有基本的电子邮件验证,并且只能输入数字“”。


有人可以帮我吗?提前致谢。


暮色呼如
浏览 83回答 2
2回答

江户川乱折腾

有多种方法可以做到这一点,但我建议在初始化为 true 的状态下跟踪按钮的禁用状态。现在在每次更改电子邮件时运行的useEffect中更改禁用状态,并根据您的验证将其设置为 true 或 false。import React from "react";// Modify this function as per your needsconst validateEmail = email => typeof email === "string" && email.includes("@");export default function App() {&nbsp; const [email, setEmail] = React.useState("");&nbsp; const [isDisabled, setIsDisabled] = React.useState(true);&nbsp; const onEmailChange = event => {&nbsp; &nbsp; setEmail(event.target.value);&nbsp; };&nbsp; React.useEffect(() => {&nbsp; &nbsp; setIsDisabled(!validateEmail(email));&nbsp; }, [email]);&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp; &nbsp; &nbsp; &nbsp; value={email}&nbsp; &nbsp; &nbsp; &nbsp; onChange={onEmailChange}&nbsp; &nbsp; &nbsp; &nbsp; placeholder="Insert user email"&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; <button disabled={isDisabled}>Add</button>&nbsp; &nbsp; </>&nbsp; );}这是codesandbox中的工作原型

繁星淼淼

您可以使用regexorder 通过onChange()属性检查输入值是否为电子邮件。import React from "react";const regex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i;export default function App() {&nbsp; const [isDisabled, setDisibility] = React.useState(true);&nbsp; const checkEmail = e => {&nbsp; &nbsp; setDisibility(!regex.test(e.target.value));&nbsp; }&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <input onChange={checkEmail} placeholder="email address" />&nbsp; &nbsp; &nbsp; <button disabled={isDisabled}>add</button>&nbsp; &nbsp; </div>&nbsp; );}https://codesandbox.io/s/dry-sun-votmt?fontsize=14&hidenavigation=1&theme=dark
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript