1

我有这个使用'formsy-react'的表单组件(在打字稿中)。使用无效表单提交后,我能够收到无效字段的名称(“onInvalidSubmit”中的变量“fieldsWithErrors”)。

我需要的是,如果字段有多个验证函数(在我的示例中为“validationFunc1”、“validationFunc2”),以了解哪个验证函数导致了无效状态。

谢谢!

import * as React from 'react';
import Formsy from 'formsy-react';
import {Input} from '../controls/Input/Input';

export class MyForm extends React.Component {
  onValidSubmit(_formData) {/**/ }
  onChange() {/**/ }

  private fields = [
    {
      id: 'fieldName',
      validations: {
        validationFunc1: () => {/* some validation*/ },
        validationFunc2: () => {/* some other validation*/ }
      }
    }
  ];

  onInvalidSubmit() {
    const fieldsWithErrors = this.getFieldsWithErrors();
    console.log(fieldsWithErrors);
  }

  getFieldsWithErrors() {
    const inputs: Formsy.WrappedComponent[] =
      (this.refs.form as any).inputs;
     const haveErrors = 
      ({props}) => !this.refs[props.name]['isValid']();
    return inputs.filter(haveErrors)
      .map(({props}) => props.name);
  }

  render() {
    return (
      <Formsy ref="form"
        onInvalidSubmit={() => this.onInvalidSubmit()}
        onValidSubmit={(formData) => this.onValidSubmit(formData)}
        onChange={() => this.onChange()}>
        {this.fields.map((field) => {
          return (
            <div key={field.id}>
              <Input
                name={field.id}
                validations={field.validations}
              /></div>);
        })}
        <button>Submit</button>
      </Formsy >
    );
  }
}
4

0 回答 0