【问题标题】:How to validate using useEffect()如何使用 useEffect() 进行验证
【发布时间】:2020-07-04 09:12:35
【问题描述】:

我正在尝试使用 useState() 和 useEffect() 验证表单

这是我的 useEffect() 方法

/ for every change in our state this will be fired
  // we add validation here and disable the save button if required
  useEffect(() => {

    // we want to skip validation on first render
    if (firstRender.current) {
      firstRender.current = false
      return
    }

    // here we can disable/enable the save button by wrapping the setState function
    // in a call to the validation function which returns true/false
    //setDisabled(formValidation())
    formValidation();

  }, [fullName,email,password]) // any state variable(s) included in here will trigger the effect to run

`我是 React JS 的新手,所以使用 if-else 完成了基本的编码。 我在这里停留的概念比技术更多。 我无法验证其他输入字段,例如电子邮件和密码。如何实现? 这是我的验证方法: // 这里我们运行任何验证,返回真/假

  const formValidation = () => {
    var error = false;
    if (fullName === "") {
      setNameError('Name cant be blank!')
      error = true;
    }

    let regEmail = /^(([^<>()\[\]\\.,;:\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,}))$/;
    if (!regEmail.test.email) {
      setEmailError('Enter a valid email id')
      error = true;
    }
    if (email === "") {
      setEmailError('Mandatory Field')
      error = true;
    }
    let regPassword = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/
    if (!regPassword.test.email) {
      // alert("errosdr")
      setPasswordError('Invalid Password Format')
      error = true;
    }

    if (error == true) {
      return true;
    }
    else {
      setNameError(null)
      setEmailError(null)
      setPasswordError(null)
      return false
    }
  }

第一个字段的验证效果很好,即 fullName。

仅供参考,这里是useState()的定义

    // we use the help of useRef to test if it's the first render
  const firstRender = useRef(true);

  // set a state variable which can be used to disable the save/submit button
  // we set it to true so that the form is disabled on first render
  const [disable, setDisabled] = useState(true);

  // set error messages to display to the user
  const [nameError, setNameError] = useState(null);
  const [emailError, setEmailError] = useState(null);
  const [passwordError, setPasswordError] = useState(null);

  // set initial state value(s)
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

【问题讨论】:

  • Formikyup 库一起使用,以便更轻松地验证表单处理。
  • @adel 感谢您的告知。现在,希望以正常方式进行。 :)

标签: javascript reactjs validation


【解决方案1】:

只要您在组件中调用 set 函数,它就会自动重新渲染。因此,在您的情况下,formValidation 调用 setNameError 并继续重新渲染,因此其余代码未执行。

在您当前的实现中,发生了这样的事情:

  • fullNameemailpassword 已更改
  • formValidation() 被调用
  • 检查fullName === "" 并调用setNameError("Name can't be blank!")
  • 组件重新渲染
  • 未调用函数中的其余逻辑。

为避免这种情况,您可能希望将错误状态存储在单个状态中:

const [errors, setErrors] = useState({})

最佳做法是在您在每个组件中创建的每个函数中只调用一个 setState。理想情况下,它是在一定的逻辑之后调用的。

这是修改后的示例formValidation

const formValidation = () => {
    let newErrors = {}
    if (fullName === "") {
      newErrors.name = 'Name cant be blank!'
    }

    let regEmail = /^(([^<>()\[\]\\.,;:\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,}))$/;
    if (!regEmail.test.email) {
      newErrors.email = 'Enter a valid email id'
    }
    if (email === "") {
      newErrors.email = 'Mandatory Field'
    }
    let regPassword = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/
    if (!regPassword.test.email) {
      newErrors.password = 'Invalid Password Format'
    }

    setErrors(newErrors)
  }

【讨论】:

  • 让它{errors.password &amp;&amp; &lt;p&gt;{errors.password}&lt;/p&gt;}
  • 如果有帮助,请注意将我的答案作为最佳答案,以便对其他读者有所帮助。谢谢!
  • 感谢@blankart 的快速响应,已解决!虽然,现在处理电子邮件正则表达式没有按预期工作。虽然,这个问题已经解决了! :)
猜你喜欢
  • 2020-08-11
  • 1970-01-01
  • 2011-01-20
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多