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

时间:2018-05-24 08:50:13

标签: forms reactjs validation jsx

我开始研究React并希望为多个输入创建表单,我可以在输入时检查数据的验证,并在提交表单之前再次检查。
要提交的条件:所有字段都是必填字段且数据有效。

目前,如果用户在输入字段中输入无效数据,则会在同一字段附近显示错误文本。如果用户在带有空字段的表单上单击“提交”按钮,则还会显示错误文本。

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

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')
)

2 个答案:

答案 0 :(得分:0)

以下代码是在提交之前通过表单和表单验证添加数据的示例。可以添加更多验证。

class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
  name: '',
  age: '',
  email: '',
  errorName: '',
  errorAge: '',
  errroMail: '',
  dataValue: false
};
this.getName = this.getName.bind(this);
this.getAge = this.getAge.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.postDatainDisplay = this.postDatainDisplay.bind(this);
}

componentWillReceiveProps(nextProps) {
    if (this.props.name !== nextProps.name) {
        this.setState({ dataValue: true });
    }
}
postDatainDisplay(dataObj) {
    this.props.postData(dataObj);
}
getName(event) {
    const { name, age } = this.state;
    this.setState({ errorName: '' });
    this.setState({ name: event });
}
getAge(event) {
   const { age } = this.state;
   this.setState({ errorAge: '' });
   this.setState({ age: event });
}
handleSubmit() {
const { name, age } = this.state;
//add more validation here 
if (name === '') {

  this.setState({ errorName: 'name cannot be blank', dataValue: false 
});

} else if (age === '') {

  this.setState({ errorAge: 'Age cannot be blank', dataValue: false });
} else
{     this.setState({ data: { name, age } }, () => {
      this.props.sendData(this.state.data);
}
render() {
const { name, age } = this.props;
return (
  <div className="container">
    <form>
      name:<input
        type="text"
        onChange={event => {
          this.getName(event.target.value);
        }}
      />
      {this.state.errorName}
      <br />
      <br />
      age:{' '}
      <input
        type="text"
        onChange={event => {
          this.getAge(event.target.value);
        }}
      />
      {this.state.errorAge}
      <br />
      <br />
       <input type="button" onClick={this.handleSubmit} value="Submit" 
       />
    </form>
    </div>

答案 1 :(得分:0)

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字段禁用提交按钮的值