在React中验证表单的最简单方法

时间:2019-01-04 02:52:01

标签: javascript reactjs redux

我不太确定如何在react中进行表单验证。

我想在当前页面上显示一条错误消息。但是,密码验证将被忽略,因此它们不会显示在页面上。

密码必须至少包含字符

也许我没有正确使用conditional rendering

SignUp.js (用于演示的代码段)

us-west-2:e8340b.....

4 个答案:

答案 0 :(得分:2)

您应该以组件的状态存储表单数据。例如,用this.state.email代替this.email。当更新以组件状态存储的数据时,将触发重新渲染。但是,不会触发rerender来更新普通类变量。设置errors时,还可以直接操纵状态。相反,您应该使用setState方法docs

在页面上看不到错误的原因是由于表单的更改导致页面未正确重新呈现。

请注意,将表单数据变量包装在组织状态下的formData对象中也是一个好主意。这有助于将表单的数据与组件其余状态分开(例如,使表单值与error变量分开),并使表单数据更容易传递,例如在提交表单期间。

以下是您如何组织事物的示例:

constructor(props){
 super(props);

 this.state = {
  formData: { // set up default form values
    email: "",
    password: "",
  },
  errors: {},
}

handleChange = event => {
  const { formData } = this.state;

  this.setState({
    formData: {
      ...formData, // leave other values unchanged
      [event.target.name]: event.target.value, // update the changed value
    }
  });
}

handleSubmit(event) {
  event.preventDefault();

  const { formData, errors } = this.state;
  const { email, password } = formData;

  if (password.length < 6) { // changed comparison to _less_ than
    this.setState({ // update errors using setState -- never directly modify a component's state
      errors: {
        ...errors,
        password: "Password must be at least 6 characters",
      }
    });
  }

  const creds = {email, password}

  if (creds.email && creds.password) { // objects are never falsey, so we need to check each field directly
    this.props.signUp(creds);
    this.props.history.push('/');

  }
}

render() {
 return (
  <div className="container">
    <div className="row">
      <div className="col-md-6">
        <h1>Sign Up</h1>
        <form onSubmit={this.handleSubmit}>
          <div className="form-group">
            <label htmlFor="exampleInputEmail1">Email address</label>

            <input
              name="email"
              type="email"          
              className="form-control"
              id="email"
              value={ this.state.formData.email } {/* control component by storing value in state and updating state when the input changes */}
              onChange={ this.handleChange }
              aria-describedby="emailHelp"
              placeholder="Enter email" />
            <small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
          </div>
          <div className="form-group">
            <label htmlFor="exampleInputPassword1">Password</label>
            {this.state.errors.password &&
               //display an error here
              <h2>{this.state.errors.password}</h2>
            }
            <input
              name="password"
              type="password"
              value={ this.state.formData.password }
              onChange={ this.handleChange }
              className="form-control"
              id="password"    
              placeholder="Password" />

          </div>



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

    </div>
  </div>

  );
 }

} 

注意:如果您的表单具有复选框输入,则显示的handleChange方法将不适用于这些字段,因为应该使用复选框输入的checked属性而不是{{1} }属性。为简单起见,我只包括了非复选框的情况,但这是value的完整版本:

handleChange

答案 1 :(得分:0)

此示例未使用组件状态来管理“密码”和“电子邮件”字段。

通过将它们作为受控输入字段,然后可以在更改时验证它们并有条件地将其呈现为错误消息(不需要保持状态)

例如如果您想显示错误是密码太短:

{ this.state.password.length < 5 && <p>Password too short</p> }

也许签出https://github.com/jaredpalmer/formik 看看一些例子。

答案 2 :(得分:0)

我认为您的代码显示错误显示使用状态

{this.state.errors.password &&
           //display an error here
          <h2>{this.state.errors.password}</h2>
        }

并以提交表格的形式更新您的状态

if(password.length > 6){
this.setState({ errors: { password: "Password must be at least 6 characters"} 

})
  } else {
this.setState({errors: {}})
}

答案 3 :(得分:0)

我已经构建了自定义钩子,可以轻松进行表单验证。我认为这会使您的生活变得更加轻松。您可以利用您的html验证知识。

Github:https://github.com/bluebill1049/react-hook-form

网站:http://react-hook-form.now.sh

import React from 'react'
import useForm from 'react-hook-form'

function App() {
  const { register, handleSubmit, errors } = useForm() // initialise the hook
  const onSubmit = (data) => { console.log(data) } // callback when validation pass

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstname" ref={register} /> {/* register an input */}

      <input name="lastname" ref={register({ required: true })} /> {/* apply required validation */}
      {errors.lastname && 'Last name is required.'} {/* error message */}

      <input name="age" ref={register({ pattern: /\d+/ })} /> {/* apply a Refex validation */}
      {errors.age && 'Please enter number for age.'} {/* error message */}

      <input type="submit" />
    </form>
  )
}