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

博客介绍了表单校验相关内容,如设置 validateTrigger: ‘onBlur’,让密码输入框失去焦点时校验以优化体验;还提到手动触发用户名校验规则,需用 getFieldDecorator() 包装用户名输入控件,且设置 force 为 true 可使已校验表单域再次校验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 再次被触发时再次校验。

完...

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值