如何使用反应钩子验证电子邮件和密码?

时间:2021-06-24 11:59:03

标签: reactjs react-hooks

我在单击提交按钮时获取状态值,但我无法验证我的登录表单以及当我输入错误或为空时如何在输入字段下方显示错误消息。请给我一个解决方案。提前致谢。

const Login = () => {
    const [state, setState] = useState({
        email: "",
        password: ""
    });
    
    const handleChange = (e) => {
        const {id, value} = e.target
        setState(prevState => ({
            ...prevState,
            [id]: value
        }))
    }

    const handleSubmitClick = (e) => {
        e.preventDefault();
        console.log("Authenticated",state);
    }

    return(
        <>
        <div className="container">
            <div className="title">
                <form onSubmit={handleSubmitClick}>
                    <div className="form-group">
                        <input 
                          type="email" 
                          className="email"
                          placeholder="Email"
                          value={state.email}
                          onChange={handleChange}/>
                    </div>
                    <div className="form-group">
                        <input 
                          type="password" 
                          className="password"
                          placeholder="Password"
                          value={state.password}
                          onChange={handleChange}/>
                    </div>
                    <button type="submit" className="button">Enter</button>
                 </form>
            </div>
        </div>
        </>
    )
}

export default Login;

3 个答案:

答案 0 :(得分:1)

如果你想执行客户端验证,你可以像这样创建钩子:

const useEmailValidation = (email) => {
  const isEmailValid = /@/.test(email); // use any validator you want
  return isEmailValid;
};

然后你可以在你的表单组件中使用这个钩子:

...
const isEmailValid = useEmailValidation(state.email);
const isPasswordValid = usePasswordValidation(state.password);
const isFormValid = isEmailValid && isPasswordValid;

return (
  ...
    <input
      className={classNames({ 'invalid': !isEmailValid })}
      type="email"
      value={state.email}
      onChange={handleChange}
    />
    {!isEmailValid && 'Some error message'}
    <button type="submit" disabled={!isFormValid} className="button">Enter</button>
  ...
);
...

您的验证器挂钩可以返回验证消息而不是布尔值,例如:

const useEmailValidation = (email) => {
  if (!email || email.length === 0) {
    return 'Email cannot be empty';
  }

  const isEmailValid = /@/.test(email); // use any validator you want
  if (!isEmailValid) {
    return 'Invalid email provided';
  }

  return null;
};

此外,仅在用户尝试提交表单之前和之后聚焦字段后才显示验证消息也是一个好习惯。

答案 1 :(得分:0)

Formik 是一个很棒的插件,可以帮助您执行表单验证。例子也很清楚。

或者你可以这样做:

const Login = () => {
  const [error, setError] = useState(null);
  const [state, setState] = useState({
    email: '',
    password: '',
  });

  const validateEmail = (email) => {
    const re =
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
  };

  const handleChange = (e) => {
    const { id, value } = e.target;
    setState((prevState) => ({
      ...prevState,
      [id]: value,
    }));
  };

  const handleSubmitClick = (e) => {
    e.preventDefault();

    if (!validateEmail(state.email)) {
      setError('Invalid Email');
    }

    if (state.password.length < 8) {
      setError('Password must be at least 8 chars long');
    }

    if (!error) {
      // No errors.
    }
  };

  return (
    <>
      <div className='container'>
        <div className='title'>
          {error && <div style={{ color: 'red' }}>{error}</div>}
          <form onSubmit={handleSubmitClick}>
            <div className='form-group'>
              <input
                type='email'
                className='email'
                placeholder='Email'
                value={state.email}
                onChange={handleChange}
              />
            </div>
            <div className='form-group'>
              <input
                type='password'
                className='password'
                placeholder='Password'
                value={state.password}
                onChange={handleChange}
              />
            </div>
            <button type='submit' className='button'>
              Enter
            </button>
          </form>
        </div>
      </div>
    </>
  );
};

export default Login;

答案 2 :(得分:0)

对于空验证,如果字段为空,您可以检查它以防止提交,例如

const handleSubmitClick = (e) => {
        e.preventDefault();
  if(email.trim() === '' || password.trim() === ''){
       //Add a h1 or section with the error message
  }else{
        console.log("Authenticated",state);
  }
}

只要电子邮件字段类型等于电子邮件,就是您的情况,如果字符串不是电子邮件,浏览器就会发出警报。 ("user@example.com")