antd 校验表单时触发对其他表单的校验

import { Form, Input } from 'antd';
import React, { Component } from 'react';

class ComponentA extends Component {
  constructor(props) {
    super(props);
  }

  /**
   * 
   * @param {} rule 
   * @param {String} vaule 
   * @param {Function} callback 
   */
  checkPsd(rule, value, callback) {
    if (value) {
      this.props.form.validateFields(['userName'], { force: true });
    }
  }
  render() {
    const FormItem = Form.Item;
    const { getFieldDecorator } = this.props.form;

    return (
      <Form>
        <FormItem label='用户名:'>
          {getFieldDecorator('userName', {
            rules: [{ required: true, message: '请输入用户名' }]
          })(
            <Input />
          )}
        </FormItem>
        <FormItem label='密码:'>
          {getFieldDecorator('password', {
            rules: [
              { required: true, message: '请输入密码' },
              { validator: (rule, value, callback) => { this.checkPsd(rule, value, callback) } }
            ],
            validateTrigger: 'onBlur'
          })(
            <Input />
          )}
        </FormItem>
      </Form>
    )
  }
}

export default Form.create()(ComponentA);

其中:validateTrigger: ‘onBlur’,当密码输入框失去焦点时才去校验,为了优化用户体验

this.props.form.validateFields[‘userName’, { force: true }]; 手动触发用户名的校验规则,注意用户名输入控件必须要经过getFieldDecorator()包装,至于为什么要进行包装,可以去官网看文档说明。另外要设置force的值为true,对已经校验过的表单域,在 validateTrigger 再次被触发时再次校验。

完…


版权声明:本文为lh_guojw原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。