简体   繁体   English

React/AntDesign 触发 Form.Item 事件重新验证

[英]React/AntDesign Trigger Form.Item Re-Validation on Event

Problem Context问题背景

I am collecting user input using an AntDesign Form inside a functional component.我正在使用功能组件内的 AntDesign 表单收集用户输入。 The user must watch a video clip and determine the relative time period where some event occurred in the video consisting of 'start-time' and 'end-time' in the form (HH:MM:SS) - (HH:MM:SS), for example, 00:05:30 - 00:05:35 (a 5 second time period).用户必须观看视频剪辑并确定视频中某些事件发生的相对时间段,该时间段由 (HH:MM:SS) - (HH:MM:SS) 形式的“开始时间”和“结束时间”组成),例如 00:05:30 - 00:05:35(5 秒时间段)。

The Form to collect this data is made up of two <Form.Items>.用于收集此数据的 Form 由两个 <Form.Items> 组成。 One to collect start-time and the other to collect end-time.一个收集开始时间,另一个收集结束时间。 (There are other cases for how the form may be constructed so the Form.Items, in this case, are returned as JSX to be wrapped in a Form in the render method.) Like so: (对于如何构造表单,还有其他情况,因此在这种情况下,Form.Items 作为 JSX 返回以包装在渲染方法中的 Form 中。)像这样:

const timeInput = () => {
    return (
        <>
        <Form.Item
            name={"start-time"}
            hasFeedback
            rules={[
                {
                    required: true,
                    message: 'Required',
                },
                ({ getFieldValue }) => ({
                    validator(_, value) {
                        return startTimeInputValidator(getFieldValue, "end-time", value)
                    }
                })
            ]}
        >
        <Input 
        id="start-time-input"
        placeholder={"Start Time (HH:MM:SS)"} />
        </Form.Item>

        <Form.Item
            name={"end-time"}
            hasFeedback
            rules={[
                {
                    required: true,
                    message: 'Required',
                },
                ({ getFieldValue }) => ({
                    validator(_, value) {
                        return endTimeInputValidator(getFieldValue, "start-time", value)
                    }
                })
            ]}
        >
        <Input 
        id="end-time-input"
        placeholder={"End Time (HH:MM:SS)"} />
        </Form.Item>
        </>
    )        
}

The input for each form item is validated with custom validators imported from a separate file:每个表单项的输入都使用从单独文件导入的自定义验证器进行验证:

const regexTime = /^(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)$/;
const timeInvalidDesc = "Not a Valid Time!";
const doStartTimeDesc = "Start Time Invalid!";
const timeMismatchDesc = "End Time must be after Start Time!";

export async function startTimeInputValidator(getFieldValue, field, text) {
    var endTime = getFieldValue(field);
    if (!text) {
        return Promise.resolve();
    }
    if(text.length<8) {
        return Promise.reject();
    }
    if (!regexTime.test(text)) {
        return Promise.reject(new Error(timeInvalidDesc));
    }
    if(regexTime.test(endTime)) {
        let stn = timeToInt(text);
        let etn = timeToInt(endTime);
        if(stn > etn) {
            return Promise.reject(new Error(timeMismatchDesc));
        }
    }
    return Promise.resolve();
}

export async function endTimeInputValidator(getFieldValue, field, text) {
    var startTime = getFieldValue(field);
    if (!text) {
        return Promise.resolve();
    }
    if(text.length<8) {
        return Promise.reject();
    }
    if (!regexTime.test(text)) {
        return Promise.reject(new Error(timeInvalidDesc));
    }
    if (!regexTime.test(startTime)) {
        return Promise.reject(new Error(doStartTimeDesc));
    }
    let stn = timeToInt(startTime);
    let etn = timeToInt(text);
    if(stn > etn) {
        return Promise.reject(new Error(timeMismatchDesc));
    }
    return Promise.resolve();
}

The validators correctly ensure that the user has entered a valid time in the form 'HH:MM:SS' and they also correctly ensure that the 'end-time' is not before the 'start-time', that is, it is impossible to submit the form if the 'end-time' is before the 'start-time' because I assume when the user submits the form the fields are re-validated.验证器正确地确保用户以“HH:MM:SS”的形式输入了有效时间,并且他们还正确地确保“结束时间”不在“开始时间”之前,也就是说,这是不可能的如果“结束时间”早于“开始时间”,则提交表单,因为我假设当用户提交表单时,字段会被重新验证。

The problem occurs when the user:当用户出现问题时:

  1. Enters a valid 'start-time' (incomplete form)输入有效的“开始时间”(不完整的表格)
    • ex: 00:00:05 - null例如:00:00:05 - 空
  2. Enters a valid 'end-time' (valid complete form)输入有效的“结束时间”(有效的完整表格)
    • ex: 00:00:05 - 00:00:10例如:00:00:05 - 00:00:10
  3. Changes the 'start-time' to be AFTER the 'end-time' (invalid complete form)将“开始时间”更改为“结束时间”之后(无效的完整表格)
    • ex: 00:00:15 - 00:00:10例如:00:00:15 - 00:00:10
  4. Changes the 'end-time' to be AFTER the new 'start-time' ( should be a valid complete form)将“结束时间”更改为在新的“开始时间”之后(应该是有效的完整表格)
    • ex: 00:00:15 - 00:00:20例如:00:00:15 - 00:00:20

Now, in the above case, the form should not show error messages given that the input is valid and the times are in the correct order, but it will still show an error message for the start-time field because during step 4 the validator for 'start-time' was not triggered.现在,在上述情况下,鉴于输入有效且时间顺序正确,表单不应显示错误消息,但它仍会显示开始时间字段的错误消息,因为在第 4 步中,验证器“开始时间”没有被触发。

Question

My question boils down to this: How can I re-validate the 'start-time' when there is a change to 'end-time' input (and vice versa) with the goal of responsive updating of error messages as the user changes their input?我的问题归结为:当“结束时间”输入发生更改(反之亦然)时,如何重新验证“开始时间”,目的是在用户更改错误消息时响应式更新错误消息输入? In other words, how can I validate both Form.Items when a change occurs to the input of either?换句话说,当任一 Form.Items 的输入发生更改时,我如何验证这两个Form.Items?

Apologies if I took too long to get to the heart of the question.如果我花了太长时间才触及问题的核心,我深表歉意。 I assume too much context is better than too little.我认为上下文太多总比太少好。 Thank you in advance.先感谢您。

You should set the dependencies property of the field "end-time"您应该设置字段“结束时间”的依赖项属性
Documentation: https://ant.design/components/form/#dependencies文档: https : //ant.design/components/form/#dependencies

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

相关问题 antd中的'Form.Item'和'div'有什么区别? - What is the difference 'Form.Item' and 'div' in antd? 蚂蚁设计Form中Form.Item中如何迭代添加Form.Item - How to iteratively add Form.Item in Form.Item in ant design Form 在 Form.Item 中包含 antd Table 时如何获取值? - How to get values when include antd Table in Form.Item? 在 AntD 中更改 form.item 标签字体大小 - Change form.item label font size in AntD 将 Antd Form.Item 转换为试剂打嗝 - Converting Antd Form.Item to reagent-hiccup React AntDesign Menu Sub Item... 让它像组件一样工作 - React AntDesign Menu Sub Item ... make it work like component 如果数据链接值不变,则在jsViews中强制重新验证 - Force re-validation in jsViews if data-linked value doesn't change ant 设计 - 使用 Form.setFieldsValue 更新 Form.Item 内复选框的选中值 - ant design - Update checked value of a checkbox inside a Form.Item using Form.setFieldsValue 在 React 中重新渲染 select 元素后触发 onChange 事件 - Trigger an onChange event after a select element is re-rendered in React 如何设置 layout=&quot;horizo​​ntal&quot; 里面的几个<Form.Item>同时保持<Form layout="vertical">在蚂蚁设计中 - How to set the layout="horizontal" inside for few <Form.Item> while keeping <Form layout="vertical"> in ant design
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM