加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:20:26 所属栏目:百科 来源:网络整理
导读:我之前使用Joi和react-validation-mixin编写了一个表单,它运行得非常好. 现在我的团队决定从旧平台迁移,现在我们正在为我们的新表单使用redux和redux-form. 我想要实现的是将旧的验证系统保持在redux-form中. 所以基本上验证部分是: import Joi from 'joi';
我之前使用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);

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

export default connect(
  state => ({
    initialValues: state.initialValues,}),)(reduxForm({
  form: 'form',})(Form));

我看到redux-form接受一个名为validate的属性,在那里我尝试通过验证(策略),但它只是生成错误……

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

问题是,在使用redux-form时,如何使用旧的react-validation-mixin策略验证我的表单?

谢谢

解决方法

它似乎不是一个完全简单的修复,但您可以通过使用Joi作为验证的基础来最小化重构的影响.由于Joi验证是异步的,你可以使用 async validation from 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));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读