javascript - 使用React进行表单验证

标签 javascript reactjs express validation axios

我正在尝试创建用户注册表单,并遇到显示表单验证错误的障碍。

问题:
1)对于没有错误的输入,输入不再在提交后将(axios)投递到db。2)错误修复后,错误消息不会消失。

旁注:我已将firstNameError,lastNameError和emailError注释为仅关注passwordError。

import React, { Component } from 'react';
import axios from 'axios';
import { Form, Container } from 'react-bootstrap'

export default class RegisterUser extends Component {
  constructor(props) {
    super(props);

    this.onChangeFirstName = this.onChangeFirstName.bind(this);
    this.onChangeLastName = this.onChangeLastName.bind(this);
    this.onChangeEmail = this.onChangeEmail.bind(this);
    this.onChangePassword = this.onChangePassword.bind(this);
    this.onSubmit = this.onSubmit.bind(this);

    this.state = {
      firstName: '',
      lastName: '',
      email: '',
      password: '',
      firstNameError: '',
      lastNameError: '',
      emailError: '',
      passwordError: '',
    }
  }

  onChangeFirstName(e) {
    this.setState({
      firstName: e.target.value
    })
  }

  onChangeLastName(e) {
    this.setState({
      lastName: e.target.value
    })
  }

  onChangeEmail(e) {
    this.setState({
      email: e.target.value
    })
  }

  onChangePassword(e) {
    this.setState({
      password: e.target.value
    })
  }

  validate() {
    // let firstNameError= '';
    // let lastNameError= '';
    //  let emailError= '';
    let passwordError = '';

    if (!this.state.password.length < 6) {
      passwordError = 'Password must be at least 6 characters'
    }

    if (passwordError) {
      this.setState({ passwordError })
      return false
    }

    return true;
  }

  onSubmit(e) {
    e.preventDefault();
    const isValid = this.validate()
    if (isValid) {
      const user = {
        firstName: this.state.firstName,
        lastName: this.state.lastName,
        email: this.state.email,
        password: this.state.password,
      }

      console.log(user);

      axios.post('http://localhost:5001/users/add', user)
        .then(res => console.log(res.data));

      this.setState({
        firstName: '',
        lastName: '',
        email: '',
        password: ''
      })
    }
  }

  render() {
    return (
      <Container>
        <h3>Register</h3>
        <Form onSubmit={this.onSubmit}>
          <Form.Group>
            <Form.Label>First name</Form.Label>
            <Form.Control
              type="text"
              id="firstName"
              required
              value={this.state.firstName}
              onChange={this.onChangeFirstName}
            />
            <div style={{ color: 'red' }}>
              {this.state.firstNameError}
            </div>
          </Form.Group>
          <Form.Group>
            <Form.Label>Last name</Form.Label>
            <Form.Control
              id="lastName"
              type="text"
              required
              value={this.state.lastName}
              onChange={this.onChangeLastName}
            />
          </Form.Group>
          <div style={{ color: 'red' }}>
            {this.state.lastNameError}
          </div>
          <Form.Group>
            <Form.Label>Email</Form.Label>
            <Form.Control
              type="email"
              id="email"
              required
              value={this.state.email}
              onChange={this.onChangeEmail}
            />
          </Form.Group>
          <div style={{ color: 'red' }}>
            {this.state.emailError}
          </div>
          <Form.Group>
            <Form.Label>Password</Form.Label>
            <Form.Control
              type="password"
              id="password"
              required
              value={this.state.password}
              onChange={this.onChangePassword}
            />
          </Form.Group>
          <div style={{ color: 'red' }}>
            {this.state.passwordError}
          </div>
          <Form.Group>
            <Form.Control
              type="submit"
              value="Register"
              className="btn btn-primary"
            />
          </Form.Group>
        </Form>
      </Container>
    )
  }
}

最佳答案

您的验证中的代码未重置错误消息。如果密码有效,则应使用以下命令重置密码:

this.setState({ passwordError: '' })


我错误地认为if(passwordError)对于一个空字符串将返回true,但事实并非如此。如果您可以使用开发人员工具在浏览器中调试代码,则可以查看为什么未发布正确的内容。这可能是因为对有效标志使用了常量。

关于javascript - 使用React进行表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60468393/

相关文章:

javascript - Node.js 发送后无法发送 header

javascript - jQuery 集合的 HTML

javascript - 跟随教程时 react 错误

javascript - 将鼠标悬停在按钮上时如何打开 material-ui 菜单

javascript - 如何在reactstrap的Popovers中正确使用delay?

javascript - 如何在 node.js 中缓存内部文件?

javascript - 在黑色背景之外单击时关闭流行通讯表单?

javascript - 火力地堡错误 : [code=unknown]: Fetching auth token failed: Cannot redefine property: refreshToken

node.js - TypeError:Router.use()需要中间件功能

javascript - Express-Validator 5.2.0 - 验证对象的通配符数组 - 比较