formy-反应如何判断哪个验证使输入无效

时间:2018-02-21 11:15:45

标签: reactjs validation formsy-react

我有这个使用' formy-react'的表单组件(在typescript中)。 在使用无效表单提交后,我可以接收无效字段的名称(变量' fieldsWithErrors' on&invalidSubmit')。

我需要的是,如果字段的多个验证函数(&#39; validationFunc1&#39;,&#39; validationFunc2&#39;在我的示例中)知道哪个验证函数导致无效状态。< / p>

谢谢!

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 >
    );
  }
}

0 个答案:

没有答案