在提交之前和数据输入时进行表单验证

问题描述:

我开始研究React,并希望为多个输入创建表单,在这里我可以在输入时以及提交表单之前再次检查数据的有效性.
提交条件:所有字段均为必填字段,数据有效.

I started to study React and wanted to create the form for multiple inputs, where I can check the validation of the data at the time of input and again before submitting of the form.
The conditions to submit: all fields are mandatory and the data is valid.

当前,如果用户在输入字段中输入了无效数据,则错误文本将显示在同一字段附近.并且,如果用户在表单上单击带有空白字段的提交"按钮,也会显示错误文本.

Currently, if user enters invalid data in input field, error text is displayed near the same field. And if user clicked button "submit" on the form with empty fields, error text is also displayed.

但是我无法真正解决这个问题,在我的示例中提交表单之前,我应该如何进行验证::表单的输入字段是否有错误.

But I can't really work it out, how should I do the validation before the submission of the form in my example: : the form has the input field with an error or not.

import React from 'react'
import { render } from 'react-dom'

const ErrorOutput = props => {
  let name = props.name
  let inputValue = props.case
  let submit = props.submit
  console.log(props.submit)
  if (name === 'firstName') {
    if (!inputValue.match(/^[a-zA-Z]+$/) && inputValue.length > 0) {
        return <span>Letters only</span>
      } else if (submit && inputValue.length === 0) {
        return <span>Required</span>
      }
    return <span></span>
  }
  if (name === 'telNo') {
    if(!inputValue.match(/^[0-9]+$/) && inputValue.length > 0) {
        return <span>Numbers only</span>
      } else if (submit && inputValue.length === 0) {
        return <span>Required</span>
      }
    return <span></span>
  }
}

class App extends React.Component {
  constructor(props){
    super(props)

    this.state = {
      firstName: '',
      telNo: '',
      submit: false
    }
  }

  handleSubmit(e){
    e.preventDefault()
    let submit = true
    this.setState ({submit: submit})
    // ... Validation
  }

  handleValidation(e) {    
    this.setState({
      [e.target.name]: e.target.value 
    })  
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit.bind(this)}>
        <div>
          <label>
            First name:
          </label>
          <input
            type='text'
            name ='firstName'
            value = {this.state.firstName}
            onChange = {this.handleValidation.bind(this)}
          />
          <ErrorOutput case={this.state.firstName} name={'firstName'} submit = {this.state.submit} />
        </div>
        <div>
          <label>
            Phone number:
          </label>
          <input
            type='tel'
            name ='telNo'
            value = {this.state.telNo}
            onChange = {this.handleValidation.bind(this)}
          />
          <ErrorOutput case={this.state.telNo} name={'telNo'} submit = {this.state.submit} />
        </div>
        <button>
          Submit
        </button> 
      </form>
    )
  }
}

render(
  <App />,
  document.getElementById('root')
)

class App extends React.Component {
  constructor(props){
    super(props)    
    this.state = {
        form:{
            firstName: {
              value: '',
              validation: {
                required: true
              },
              valid: false,
              touched: false
            },
            telNo: {
              value: '',
              validation: {
                required: true
              },
              valid: false,
              touched: false
            }
         },
         formIsValid:false
      }
    }
    checkValidity(value, rules) {
        let isValid = true;

        if (rules.required) {
          isValid = value.trim() !== '' && isValid;
        }
        return isValid;
      }

    handleValidation = (event) => {
        let fieldName = event.target.name;
        let fieldValue = event.target.value;
        const updatedCategoryForm = {
          ...this.state.form
        };
        const updatedFormElement = {
          ...updatedCategoryForm[fieldName]
        };
        updatedFormElement.touched = true;
        updatedFormElement.value = fieldValue;
        updatedFormElement.valid = this.checkValidity(updatedFormElement.value, updatedFormElement.validation);
        if (!updatedFormElement.valid && updatedFormElement.validation ) {
          updatedFormElement.elementValidation = "Invalid";
        } else {
          updatedFormElement.elementValidation = "";
        }
        updatedCategoryForm[fieldName] = updatedFormElement;

        let formIsValid = true;
        for (let inputIdentifier in updatedCategoryForm) {
          formIsValid = updatedCategoryForm[inputIdentifier].valid && formIsValid;
        }
        this.setState({ form: updatedCategoryForm, formIsValid: true });
      }

基于 formIsValid 字段的值禁用提交按钮

Based on the value of formIsValid field disable submit button