简体   繁体   English

使用 React 进行表单验证

[英]Form validation with React

I'm attempting to create a user registration form and running into a roadblock with displaying form validation errors.我正在尝试创建用户注册表并遇到显示表单验证错误的障碍。

Problems: 1) The input no longer posts (axios) to the db upon submission for inputs that don't have errors 2) The error message does not go away upon the error being fixed.问题: 1) 对于没有错误的输入,在提交时,输入不再将 (axios) 发布到 db 2) 错误消息在修复错误后不会消失。

Side note: I've commented out the firstNameError, lastNameError, and emailError as to only focus on the passwordError.旁注:我已将 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>
    )
  }
}

The error message is not being reset by your code in validate.您的验证代码未重置错误消息。 If the password is valid it should be reset with:如果密码有效,则应使用以下命令重置:

this.setState({ passwordError: '' })

I wrongly assumed if(passwordError) would return true for an empty string, but it does not.我错误地认为if(passwordError)会为空字符串返回 true,但事实并非如此。 If you're able to debugg your code in the browser with developer tools you might be able to see why correct content does not get posted.如果您能够使用开发人员工具在浏览器中调试您的代码,您可能会明白为什么没有发布正确的内容。 It might be a result of using a constant for the valid flag.这可能是对有效标志使用常量的结果。

Found the issue.发现问题。 One piece was on the backend, but the other piece was in the code on original post, where I had an exclamation mark within the password validation error that should not have been there.一块在后端,但另一块在原始帖子的代码中,我在密码验证错误中有一个不应该存在的感叹号。

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

Worked when I changed it to:当我将其更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM