简体   繁体   English

Ant 设计 4 验证来自数组的表单项

[英]Ant design 4 validate form items from array

I have rendered a form item using an array.我已经使用数组呈现了一个表单项。 I want to write a custom validation to check whether the allocation fields sum up too 100 and not more or less than 100. How do I get the related allocation fields using getFieldValue?我想编写一个自定义验证来检查分配字段的总和是否超过 100 且不大于或小于 100。如何使用 getFieldValue 获取相关的分配字段?

 <Form.Item
  label="Allocation "
  name={["userBeneficiary", `${index}`, "allocation"]}
  rules={[
    ({ getFieldValue }) => ({
      validator(_, value) {
        console.log(
          "fields value from allocation",
          getFieldValue("allocation")
        );
        if (!value && getFieldValue("allocation") === "") {
          return Promise.reject("please input allocation!");
        }
        return Promise.resolve();
      },
    }),
  ]}
>
  <Input disabled={uploadState.upload.formDisabled} />
</Form.Item>

https://codesandbox.io/s/react-antd-form-array-fmp46?file=/index.js https://codesandbox.io/s/react-antd-form-array-fmp46?file=/index.js

I've just written the codesandbox for your problem As you can see on the code, you can get the value by form.getFieldValue(['userBeneficiary', ${index} ,'allocation'])我刚刚为您的问题编写了代码框正如您在代码中看到的那样,您可以通过 form.getFieldValue(['userBeneficiary', ${index} ,'allocation']) 获取值

Update:更新:

According to your request, I've added the validators.根据您的要求,我添加了验证器。 You can see the codesandbox你可以看到codesandbox

import React from 'react'
import ReactDOM from 'react-dom'
import { Form, Button, InputNumber } from 'antd'
import 'antd/dist/antd.css'
import './index.css'

const MyForm = () => {
  const mockdata = ['a', 'b', 'c']
  const [form] = Form.useForm()

  return (
    <Form form={form}>
      Hello
      {mockdata.map((item, index) => (
        <Form.Item
          label="Allocation "
          name={['userBeneficiary', `${index}`, 'allocation']}
          rules={[
            {
              required: true,
              message: 'This field is required!'
            },
            {
              type: 'number',
              message: 'Please input number!'
            },
            ({ getFieldValue }) => ({
              validator(rule, value) {
                if (index < mockdata.length - 1) {
                  return Promise.resolve()
                }
                let sum = 0
                for (let i in mockdata) {
                  sum += parseInt(
                    getFieldValue(['userBeneficiary', i, 'allocation']),
                    10
                  )
                }
                if (sum >= 100) {
                  return Promise.reject('Sum should be less than 100!')
                }
                return Promise.resolve()
              }
            })
          ]}
        >
          <InputNumber min={0} max={1000} />
        </Form.Item>
      ))}
      <Button type="primary" htmlType="submit">
        Submit
      </Button>
    </Form>
  )
}

ReactDOM.render(
  <div className="App">
    <MyForm />
  </div>,
  document.getElementById('root')
)


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM