Reactjs 中的 Antd 步骤表单验证

发布于 2025-01-17 19:41:08 字数 2550 浏览 5 评论 0原文

我一直在尝试与ANTD进行步骤创建形式验证,但我正在努力验证部分。我的目标是,如果字段未正确填充,我无法单击下一步。据我了解,我必须每次点击下一步单击时都会提交表单,但是由于我是一个初学者,我不知道该如何使用嵌套组件进行操作。配置文件组件嵌套在第三步中。你能帮我吗?

const { Step } = Steps;

const steps = [
    {
        title: 'First',
        content: 'First-content',
    },
    {
        title: 'Second',
        content: 'Second-content',
    },
    {
        title: 'third',
        content: <Profile/>,
    },
    {
        title: 'last',
        content: 'Third',
    },
];

const ListingSteps = () => {
    const [current, setCurrent] = useState(0);
    const onChange = current =>{
        setCurrent(current)
    }
 const next = () => {
        setCurrent(current + 1);
    };

    const prev = () => {
        setCurrent(current - 1);
    };

    return (
        <>
            <Steps current={current} onChange={onChange}>
                {steps.map(item => (
                    <Step key={item.title} title={item.title} />
                ))}
            </Steps>
            <div className="steps-content">{steps[current].content}</div>
            <div className="steps-action">
                {current < steps.length - 1 && (
                    <Button type="primary" onClick={() => next()}>
                        Next
                    </Button>
                )}
                {current === steps.length - 1 && (
                    <Button type="primary" onClick={() => message.success('Processing complete!')}>
                        Done
                    </Button>
                )}
                {current > 0 && (
                    <Button style={{ margin: '0 8px' }} onClick={() => prev()} >
                        Previous
                    </Button>
                )}
            </div>
        </>
    );

轮廓

function Profile() {
    
    return(
        <>
           <Form name="profile" >
                            <Form.Item  name="name" label='Name' rules={[{required:true, message:'Please enter your name' }]}>
                                <Input/>
                            </Form.Item>
                            <Form.Item name="surname" label='Surname' rules={[{required:true, message:'Please enter your name' }]}>
                                <Input/>
                            </Form.Item>
           </Form>
        </>
            

i have been trying to create form validation in steps with Antd, but I am struggling with the validation part. My goal is that i cannot click next if fields are not filled correctly. As i understand, i have to make form submit every time I click next, but since I am a beginner i don't know how to do it with nested components. Profile component is nested inside third step. Can you please help me?

const { Step } = Steps;

const steps = [
    {
        title: 'First',
        content: 'First-content',
    },
    {
        title: 'Second',
        content: 'Second-content',
    },
    {
        title: 'third',
        content: <Profile/>,
    },
    {
        title: 'last',
        content: 'Third',
    },
];

const ListingSteps = () => {
    const [current, setCurrent] = useState(0);
    const onChange = current =>{
        setCurrent(current)
    }
 const next = () => {
        setCurrent(current + 1);
    };

    const prev = () => {
        setCurrent(current - 1);
    };

    return (
        <>
            <Steps current={current} onChange={onChange}>
                {steps.map(item => (
                    <Step key={item.title} title={item.title} />
                ))}
            </Steps>
            <div className="steps-content">{steps[current].content}</div>
            <div className="steps-action">
                {current < steps.length - 1 && (
                    <Button type="primary" onClick={() => next()}>
                        Next
                    </Button>
                )}
                {current === steps.length - 1 && (
                    <Button type="primary" onClick={() => message.success('Processing complete!')}>
                        Done
                    </Button>
                )}
                {current > 0 && (
                    <Button style={{ margin: '0 8px' }} onClick={() => prev()} >
                        Previous
                    </Button>
                )}
            </div>
        </>
    );

PROFILE

function Profile() {
    
    return(
        <>
           <Form name="profile" >
                            <Form.Item  name="name" label='Name' rules={[{required:true, message:'Please enter your name' }]}>
                                <Input/>
                            </Form.Item>
                            <Form.Item name="surname" label='Surname' rules={[{required:true, message:'Please enter your name' }]}>
                                <Input/>
                            </Form.Item>
           </Form>
        </>
            

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼中杀气 2025-01-24 19:41:08

使用form.validateFields()
当您单击“下一步”按钮时,您可以通过在 validateFields 中传递所有字段 name 来检查当前步骤的所有必填字段。
例如,在您的配置文件组件中,您有两个字段:name & 姓氏
您可以通过以下方式验证字段:

const onNext = async () => {
        try {
            await form.validateFields(['name', 'surname']);
            setCurrent((prev)=>prev + 1);
        } catch {}
    };

在步骤列表的每个对象中再添加一个键,并为该步骤组件传递一组表单字段名称。

const steps = [
    {
        title: 'third',
        content: <Profile/>,
        fields: ['name', 'surname']
    },
    ....
];

现在,您可以通过从步骤数组获取每个步骤字段来验证每个步骤组件。

await form.validateFields(steps[current].fields);

检查 FormInstance API:
https://ant.design/components/form/#FormInstance

Use form.validateFields().
When you click on Next button, you can check the all the required fields for current Step by passing all the fields name in validateFields.
For example, in your Profile Component, you have two Fields: name & Surname
You can validate the fields by:

const onNext = async () => {
        try {
            await form.validateFields(['name', 'surname']);
            setCurrent((prev)=>prev + 1);
        } catch {}
    };

Add one more key in each object of step list and pass an array of form field name in for that Step component.

const steps = [
    {
        title: 'third',
        content: <Profile/>,
        fields: ['name', 'surname']
    },
    ....
];

Now you can validate each step component by getting each step fields from steps array.

await form.validateFields(steps[current].fields);

Check the FormInstance API:
https://ant.design/components/form/#FormInstance

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文