[英]Ant design 4 validate form items from array
我已經使用數組呈現了一個表單項。 我想編寫一個自定義驗證來檢查分配字段的總和是否超過 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
我剛剛為您的問題編寫了代碼框正如您在代碼中看到的那樣,您可以通過 form.getFieldValue(['userBeneficiary', ${index}
,'allocation']) 獲取值
根據您的要求,我添加了驗證器。 你可以看到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.