欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

antd form表单验证,表单初始值

程序员文章站 2022-03-02 11:54:24
...

form.setFieldsValue(initialValues);实现设置初始默认值
form.validateFields()实现对输入的值进行验证

完整代码如下:

import React, { useState, useEffect } from 'react';
import { Button, Form, Modal, Input, } from 'antd';
import _ from 'lodash';
import { connect, useIntl } from 'umi';
import styles from './PaneSvgAddLabelModal.less';
function PaneSvgAddLabelModal({ visible, onCancel, onOk, currentType,currentLabel }) {
  const intl = useIntl();
  const [form] = Form.useForm();
  useEffect(() => {
    const initialValues = {
      nameIntl_zh: currentLabel?.node?.nameIntl && currentLabel.node.nameIntl['zh-cn'],
      nameIntl_en: currentLabel?.node?.nameIntl && currentLabel.node.nameIntl['en-us'],
    };
    form.setFieldsValue(initialValues);
  },[currentLabel]);
  function handleConfirm() {
    form.validateFields().then(values => {
      const nameIntl = {
          'zh-cn': values.nameIntl_zh,
          'en-us': values.nameIntl_en,
      };
      onOk(nameIntl);
    });
  }
  function handleCancel() {
    onCancel();
  }
  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 17 },
  };
  return (
    <Modal
      visible={visible}
      title={
        currentType==='Add'?intl.formatMessage({ id: 'company.manager.detail.svg-info-add-label-title' })
        :currentType==='Rename'?intl.formatMessage({ id: 'company.manager.detail.svg-info-label-rename-title' }):null
      }
      onOk={handleConfirm}
      onCancel={handleCancel}
      footer={null}
    >
      <Form form={form} hideRequiredMark>
        <Form.Item
          {...formItemLayout}
          label={intl.formatMessage({ id: 'language.chinese' })}
          name="nameIntl_zh"
          key='nameIntl_zh'
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'placeholder.enter' }),
            },
          ]}
        >
          <Input placeholder={intl.formatMessage({ id: 'placeholder.enter' })}/>
        </Form.Item>
        <Form.Item
          {...formItemLayout}
          label={intl.formatMessage({ id: 'language.english' })}
          name="nameIntl_en"
          key='nameIntl_en'
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'placeholder.enter' }),
            },
          ]}
        >
          <Input placeholder={intl.formatMessage({ id: 'placeholder.enter' })}/>
        </Form.Item>
      </Form>
      <div className={styles.PaneSvgEditButtonWrap}>
        <Button value="cancel" className={styles.PaneSvgEditButtonCancel} onClick={handleCancel}>{intl.formatMessage({ id: `btn.cancel` })}</Button>
        <Button value="submit" onClick={handleConfirm} className={styles.PaneSvgEditButtonConfirm}>{intl.formatMessage({ id: `btn.confirm` })}</Button>
      </div>
    </Modal>
  );
}

export default connect(({ user }) => ({
}))(PaneSvgAddLabelModal);

 

相关标签: antd