使用react-validation-mixin验证redux-form

Aye*_*azo 5 validation reactjs joi redux redux-form

我之前使用Joi和编写了一个表单react-validation-mixin并且它运行得很好.

现在我的团队决定从旧平台迁移,现在我们正在使用redux,并redux-form为我们的新形式.

我想要实现的是保持旧的验证系统redux-form.

所以基本上验证部分是:

import Joi from 'joi';
import validation from 'react-validation-mixin';
import strategy from 'joi-validation-strategy';
import classnames from 'classnames';

class Form extends Component {
  constructor(props) {
    super(props);

    this.validatorTypes = {
      screenName: Joi.string().label('Screen Name'),
      ...
    };

    this.getValidatorData = this.getValidatorData.bind(this);
    this.renderHelpText = this.renderHelpText.bind(this);
    this.getClasses = this.getClasses.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  onChange(field) {
    return (event) => {
      const { value } = event.target;
      this.props.updateField(field, value);
    };
  }

  getValidatorData() {
    return this.props;
  }

  getClasses(field) {
    const { isValid } = this.props;
    return classnames({
      'form-group': true,
      'has-error': !isValid(field),
    });
  }

  renderHelpText(message) {
    return (
      <span className="validation-error-message">{message}</span>
    );
  }

  render() {
    return (
      ...
    );
  }
}

export default validation(strategy)(Form);
Run Code Online (Sandbox Code Playgroud)

我们添加后,我们redux-form的导出更改为:

export default connect(
  state => ({
    initialValues: state.initialValues,
  }),
)(reduxForm({
  form: 'form',
})(Form));
Run Code Online (Sandbox Code Playgroud)

我看到redux-form接受一个叫做的属性validate,在那里我尝试过,validation(strategy)但它只会产生错误......

我也尝试将包括它在内的出口链接起来,但它根本不起作用......

现在的问题是,我该如何使用我的老验证我的形式react-validation-mixin战略,Joi同时使用redux-form

谢谢

小智 0

这似乎不是一个完全简单的修复,但您可以通过使用 Joi 作为验证的基础来最大程度地减少重构的影响。由于 Joi 验证是异步的,因此您可以使用redux-forms 中的异步验证。那看起来像这样:

import Joi from 'joi';
import strategy from 'joi-validation-strategy';
...

class Form extends Component {
   ...
}

//ideally put this in a utility file so you can use it anywhere you have form validation
const asyncJoiValidationWrapper = (schema) => {
   return (reduxFormValues) => {
      strategy().validate(reduxFormValues, schema, {}, errors => {

         //joi validation errors should be in the error format redux-forms needs
         //i.e. {screenName: 'Screen Name is not valid'}
         throw errors;
      });
   }
}  

//take this out of your constructor
const validatorTypes = {
  screenName: Joi.string().label('Screen Name'),
  ...
};

export default connect(
   state => ({
      initialValues: state.initialValues,
}),
)(reduxForm({
   form: 'form',
   asyncValidate: asyncJoiValidationWrapper(validatorTypes)
})(Form));
Run Code Online (Sandbox Code Playgroud)