Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何使用react钩子为电子邮件和密码编写验证_Reactjs_Validation_React Hooks - Fatal编程技术网

Reactjs 如何使用react钩子为电子邮件和密码编写验证

Reactjs 如何使用react钩子为电子邮件和密码编写验证,reactjs,validation,react-hooks,Reactjs,Validation,React Hooks,我在那个项目中从事React的工作,我正试图通过React为电子邮件和密码编写验证 使用react钩子,但我不知道如何开始编写,所以请帮助实现这一点。 我想要的正是我硬编码的电子邮件和密码在我的代码。现在我只想写电子邮件和密码的验证。我想要的是,如果我输入了错误的电子邮件和正确的密码,那么在验证中,它必须只显示请输入有效的电子邮件地址。 如果我输入正确的电子邮件,那么它必须显示请输入正确的密码。如果两者都是错误的意思,那么它必须显示验证,请输入正确的电子邮件和密码 这是我的密码 import R

我在那个项目中从事React的工作,我正试图通过React为电子邮件和密码编写验证 使用react钩子,但我不知道如何开始编写,所以请帮助实现这一点。 我想要的正是我硬编码的电子邮件和密码在我的代码。现在我只想写电子邮件和密码的验证。我想要的是,如果我输入了错误的电子邮件和正确的密码,那么在验证中,它必须只显示请输入有效的电子邮件地址。 如果我输入正确的电子邮件,那么它必须显示请输入正确的密码。如果两者都是错误的意思,那么它必须显示验证,请输入正确的电子邮件和密码

这是我的密码

import React, { useState } from 'react';
import './Login.css';

const Login = () => {

    const [loginData, setLoginData] = useState(null)

    const loginCredentials = () => {
        if (loginData.email === 'john@gmail.com' && loginData.password === 'christina') {
        } else {
        }
    }


    const handleChange = ({ target }) => {
        const { name, value } = target
        const newData = Object.assign({}, loginData, { [name]: value })
        setLoginData(newData)
    }


    const handleSubmit = (e) => {
        e.preventDefault()
        loginCredentials()
    }  

return (
        <div className='container'>
            <div className='row justify-content-center'>
                <div className='col-4'>
                    <div className='mainform mt-3'>
                        <form onSubmit={handleSubmit}>
                            <div className="form-group">
                                <label htmlFor="email">Email</label>
                                <input type="email" name='email' className="form-control" id="email" onChange={handleChange}></input>
                            </div>
                            <div className="form-group">
                                <label htmlFor="password">Password</label>
                                <input type="password" name='password' className="form-control" id="password" onChange={handleChange}></input>
                            </div>
                    
                            <button type="submit"  className="btn btn-primary">Submit</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Login
import React,{useState}来自“React”;
导入“./Login.css”;
常量登录=()=>{
常量[loginData,setLoginData]=useState(null)
const loginCredentials=()=>{
如果(loginda.email=='john@gmail.com“&&loginda.password===”克里斯蒂娜“){
}否则{
}
}
常量handleChange=({target})=>{
常量{name,value}=target
const newData=Object.assign({},loginda,{[name]:value})
setLoginData(新数据)
}
常量handleSubmit=(e)=>{
e、 预防默认值()
loginCredentials()
}  
返回(
电子邮件
密码
提交
)
}
导出默认登录名

尝试将错误保存在数组中,并在末尾检查数组的长度

const [errors,setErrors]=useState([]);
.
.
.
if(username !='john@gmail.com')
{
   setErrors([...errors,{error:'Invalid username'}])
}
if(password!='something')
{
   setErrors([...errors,{error:'Invalid password'}])
}
现在在组件内部

{errors?errors.map(elem=>elem.error):null}

尝试将错误保存在数组中,并在末尾检查数组的长度

const [errors,setErrors]=useState([]);
.
.
.
if(username !='john@gmail.com')
{
   setErrors([...errors,{error:'Invalid username'}])
}
if(password!='something')
{
   setErrors([...errors,{error:'Invalid password'}])
}
现在在组件内部

{errors?errors.map(elem=>elem.error):null}

您可以创建错误消息的状态,并根据电子邮件和密码的组合不正确来更改其值。如果

const [errorMessage, setErrorMessage] = useState('')
const loginCredentials = () => {
        if (loginData.email !== 'john@gmail.com' && loginData.password !== 'christina') {
         setErrorMessage('email and pw are both incorrect')
        } else if (loginData.email !== 'john@gmail.com' {
         setErrorMessage('email is incorrect')
        } else if {.....etc
    }


然后将{errorMessage}放入jsx中您希望它显示的位置

您可以为错误消息创建一个状态,并根据电子邮件和密码的组合不正确来更改其值。如果

const [errorMessage, setErrorMessage] = useState('')
const loginCredentials = () => {
        if (loginData.email !== 'john@gmail.com' && loginData.password !== 'christina') {
         setErrorMessage('email and pw are both incorrect')
        } else if (loginData.email !== 'john@gmail.com' {
         setErrorMessage('email is incorrect')
        } else if {.....etc
    }


然后将{errorMessage}放在jsx中您希望它显示的地方

如果需要,您可以使用nested

const[error,setError]=useState(“”);
const loginCredentials=()=>{
如果(loginda.email==”john@gmail.com") {
如果(loginda.password==“克里斯蒂娜”){
设置错误(“”);
返回true;
}
其他的
{
设置错误(“不正确的密码”);
返回false;
}
}否则{
设置错误(“不正确的电子邮件和密码”);
返回false;
}
};
要显示错误,您可以在表单中的某个位置放置一个div,该div仅在出现错误时显示


{error&&{error}}

如果需要,可以使用嵌套

const[error,setError]=useState(“”);
const loginCredentials=()=>{
如果(loginda.email==”john@gmail.com") {
如果(loginda.password==“克里斯蒂娜”){
设置错误(“”);
返回true;
}
其他的
{
设置错误(“不正确的密码”);
返回false;
}
}否则{
设置错误(“不正确的电子邮件和密码”);
返回false;
}
};
要显示错误,您可以在表单中的某个位置放置一个div,该div仅在出现错误时显示


{error&&{error}

首先,您的输入值不是受控元素。了解“受控组件”

有很多方法可以做到这一点。 我认为您可以添加一个自定义钩子来处理onChange和reset处理程序

自定义挂钩:

import { useState } from 'react';

const useInputState = (initialValues) => {
  const [state, setstate] = useState(initialValues);

  const onChangeHandler = (e) => setstate({
    ...state,
    [e.target.name]: e.target.value,
  });

  const reset = (field) => {
    if (field) {
      setstate({
        ...state,
        [field]: initialValues[field],
      });
    } else {
      setstate({
        ...initialValues,
      });
    }
  };

  return [state, onChangeHandler, reset];
};

export default useInputState;

然后使用组件中的钩子

import React, { useState } from 'react';
import UseInputState from '../hooks/useInputState';

const App = () => {
  const [value, onChangeHandler, reset] = UseInputState('');

  console.log({ value });

  const [emailAlert, setEmailAlert] = useState(null);
  const [passwordAlert, setPasswordAlert] = useState(null);

  const loginCredentials = () => {
    setEmailAlert(null);
    setPasswordAlert(null);
    const { email, password } = value;
    if (email !== 'john@gmail.com') {
      setEmailAlert('Please Enter valid Email Address');
    }
    if (password !== 'christina') {
      setPasswordAlert(' please enter correct password');
    }

    reset('');

    if (password === 'christina' && email === 'john@gmail.com') {
      setEmailAlert(null);
      setPasswordAlert(null);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    loginCredentials();
  };

  return (
    <div className='container'>
      <div className='row justify-content-center'>
        <div className='col-4'>
          <div className='mainform mt-3'>
            <form onSubmit={handleSubmit}>
              <div className='form-group'>
                <label htmlFor='email'>Email</label>
                <input
                  type='email'
                  name='email'
                  className='form-control'
                  id='email'
                  value={value.email || ''}
                  onChange={onChangeHandler}
                ></input>
              </div>
              <div className='form-group'>
                <label htmlFor='password'>Password</label>
                <input
                  type='password'
                  name='password'
                  className='form-control'
                  id='password'
                  value={value.password || ''}
                  onChange={onChangeHandler}
                ></input>
              </div>

              <button type='submit' className='btn btn-primary'>
                Submit
              </button>
            </form>

            {emailAlert && <div>{emailAlert}</div>}
            {passwordAlert && <div>{passwordAlert}</div>}
          </div>
        </div>
      </div>
    </div>
  );
};

export default App;

import React,{useState}来自“React”;
从“../hooks/UseInputState”导入UseInputState;
常量应用=()=>{
const[value,onChangeHandler,reset]=UseInputState(“”);
log({value});
const[emailAlert,setEmailAlert]=useState(null);
const[passwordAlert,setPasswordAlert]=useState(null);
const loginCredentials=()=>{
setEmailAlert(空);
setPasswordAlert(空);
const{email,password}=value;
如果(电子邮件!=='john@gmail.com') {
setEmailAlert('请输入有效的电子邮件地址');
}
如果(密码!='christina'){
setPasswordAlert('请输入正确的密码');
}
重置(“”);
如果(密码=='christina'&&email=='john@gmail.com') {
setEmailAlert(空);
setPasswordAlert(空);
}
};
常量handleSubmit=(e)=>{
e、 预防默认值();
loginCredentials();
};
返回(
电子邮件
密码
提交
{emailAlert&&{emailAlert}
{passwordAlert&&{passwordAlert}}
);
};
导出默认应用程序;

首先,您的输入值不是受控元素。了解“受控组件”

有很多方法可以做到这一点。 我认为您可以添加一个自定义钩子来处理onChange和reset处理程序

自定义挂钩:

import { useState } from 'react';

const useInputState = (initialValues) => {
  const [state, setstate] = useState(initialValues);

  const onChangeHandler = (e) => setstate({
    ...state,
    [e.target.name]: e.target.value,
  });

  const reset = (field) => {
    if (field) {
      setstate({
        ...state,
        [field]: initialValues[field],
      });
    } else {
      setstate({
        ...initialValues,
      });
    }
  };

  return [state, onChangeHandler, reset];
};

export default useInputState;

然后使用组件中的钩子

import React, { useState } from 'react';
import UseInputState from '../hooks/useInputState';

const App = () => {
  const [value, onChangeHandler, reset] = UseInputState('');

  console.log({ value });

  const [emailAlert, setEmailAlert] = useState(null);
  const [passwordAlert, setPasswordAlert] = useState(null);

  const loginCredentials = () => {
    setEmailAlert(null);
    setPasswordAlert(null);
    const { email, password } = value;
    if (email !== 'john@gmail.com') {
      setEmailAlert('Please Enter valid Email Address');
    }
    if (password !== 'christina') {
      setPasswordAlert(' please enter correct password');
    }

    reset('');

    if (password === 'christina' && email === 'john@gmail.com') {
      setEmailAlert(null);
      setPasswordAlert(null);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    loginCredentials();
  };

  return (
    <div className='container'>
      <div className='row justify-content-center'>
        <div className='col-4'>
          <div className='mainform mt-3'>
            <form onSubmit={handleSubmit}>
              <div className='form-group'>
                <label htmlFor='email'>Email</label>
                <input
                  type='email'
                  name='email'
                  className='form-control'
                  id='email'
                  value={value.email || ''}
                  onChange={onChangeHandler}
                ></input>
              </div>
              <div className='form-group'>
                <label htmlFor='password'>Password</label>
                <input
                  type='password'
                  name='password'
                  className='form-control'
                  id='password'
                  value={value.password || ''}
                  onChange={onChangeHandler}
                ></input>
              </div>

              <button type='submit' className='btn btn-primary'>
                Submit
              </button>
            </form>

            {emailAlert && <div>{emailAlert}</div>}
            {passwordAlert && <div>{passwordAlert}</div>}
          </div>
        </div>
      </div>
    </div>
  );
};

export default App;

import React,{useState}来自“React”;
从“../hooks/UseInputState”导入UseInputState;
常量应用=()=>{
const[value,onChangeHandler,reset]=UseInputState(“”);
log({value});
const[emailAlert,setEmailAlert]=useState(null);
const[passwordAlert,setPasswordAlert]=useState(null);
const loginCredentials=()=>