如何在React中调用onChange和onSubmit的验证?

时间:2018-02-23 09:58:13

标签: javascript reactjs validation ecmascript-6 react-dom

柯伦 寻找在onChangeonSubmit上验证表单的解决方案,而不是在页面加载时显示无效,并且不检查onSubmit中的DOM。

当前 onSubmit函数,它检查状态值而不是输入

的DOM
  onSubmit = event => {
    event.preventDefault();
    const isFormValid = this.state.fillables.every((element) => this.state[element].isValid);
    if (isFormValid) {
            console.log('it is valid');
      const formData = this.state.fillables.map(key => { return { [key]: this.state[key]['val']} });
      this.props.onSubmit(this.state);
    }
    this.clearFormData();
  }

验证状态

  constructor(props) {
    super(props);
    this.state = {
      passwordType: 'password',
      fillables: ['firstName', 'lastName', 'email', 'username', 'password', 'terms'], // this is done through manual listing in array so that you have control which fields should be validated for before submit
      firstName: {
        val: '',
        isValid: false,
        error: 'Please enter your first name'
      },
      lastName: {
        val: '',
        isValid: false,
        error: 'Please enter your last name'
      },
      username: {
        val: '',
        isValid: false,
        error: 'Please enter username'
      },
      email: {
        val: '',
        isValid: false,
        error: 'Please enter valid email address'
      },
      password: {
        val: '',
        isValid: false,
        error: 'Please enter password'
      },
      terms: {
        val: true,
        isValid: false,
        error: 'Please agree terms and conditions'
      }
    };
  }

验证onChange

  validateForStringChars(str) {
    const re = /\b[^\d\W]+\b/g;
    const preparedStr = str.replace(/ /g, '');
    return re.test(preparedStr);
  }

  validateForEmail(str) {
    const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(str);
  }

  onChange = (event) => {
    const input = event.target;
    let inputValidationResult = false;
    switch (input.name) {
      case 'firstName':
        inputValidationResult = this.validateForStringChars(input.value) && input.value.length > 0;
        break;
      case 'lastName':
        inputValidationResult = this.validateForStringChars(input.value) && input.value.length > 0;
        break;
      case 'username':
        inputValidationResult = input.value.length > 0;
        break;
      case 'email':
        inputValidationResult = this.validateForEmail(input.value) && input.value.length > 0;
        break;
      case 'password':
        inputValidationResult = input.value.length > 0;
        break;
      case 'terms':
        inputValidationResult = input.checked;
        break;
      default:
        inputValidationResult = false;
    }
    this.setState({
      [input.name]: {
        ...this.state[input.name],
        val: input.value,
        isValid: inputValidationResult
      }
    });
  }

回购https://github.com/pshanoop/react-learn/tree/validation-ui

表格https://github.com/pshanoop/react-learn/blob/validation-ui/client/components/form/Form.js

0 个答案:

没有答案