如何验证一个数字是否大于其他内部形式规则?

发布于 2025-02-06 17:01:03 字数 2119 浏览 1 评论 0原文

表单包含两个项目,这两个项目都是接受一个数字的输入字段。我需要检查第一个输入(start)中输入的值是否总是小于第二(end),否则请显示验证错误。

以上是ANTD表单中的包装器,每个包装器都是form.item。 我需要这样的显示验证消息,

const App = () => {
  const [start, setStart] = useState(1);
  const [end, setEnd] = useState(2);
  const formRef = useRef();

  const handleSubmit = () => {
    if (end < start) {
      console.log("End cannot be lesser than start");
    } else if (end === start) {
      console.log("End cannot be same as start");
    } else {
      console.log("Added :)", start, end);
    }
  };

  return (
    <Form
      onFinish={handleSubmit}
      layout="vertical"
      ref={formRef}
      requiredMark={false}
    >
      <div>
        <Form.Item
          name="formStart"
          rules={[
            {
              required: true,
              message: "Please select a form start"
            }
          ]}
        >
          <InputNumber
            placeholder="Start"
            min={1}
            max={100}
            onChange={(e) => setStart(e)}
          />
        </Form.Item>
        <Form.Item
          name="formEnd"
          rules={[
            {
              required: true,
              message: "Please select a form end"
            }
          ]}
        >
          <InputNumber
            placeholder="End"
            min={1}
            max={100}
            onChange={(e) => setEnd(e)}
          />
        </Form.Item>
        <Form.Item>
          <button htmlType="submit">Submit</button>
        </Form.Item>
      </div>
    </Form>
  );
};

​.io/s/basic-usage-antd-4-21-0-forked-4sri66?file=/demo.js" rel="nofollow noreferrer">https://codesandbox.io/s/basic-usage-antd -4-21-0-Forked-4SRI66?file =/demo.js

Form contains two items, both of it is an input field that accepts a number. I need to check if the value entered in the first input (start) is always less than the second (end) or else, show a validation error.

UI

The above is wrapper inside antd form and each of it is a Form.Item.
I need show validation message like this,

Validation error expected

Code:

const App = () => {
  const [start, setStart] = useState(1);
  const [end, setEnd] = useState(2);
  const formRef = useRef();

  const handleSubmit = () => {
    if (end < start) {
      console.log("End cannot be lesser than start");
    } else if (end === start) {
      console.log("End cannot be same as start");
    } else {
      console.log("Added :)", start, end);
    }
  };

  return (
    <Form
      onFinish={handleSubmit}
      layout="vertical"
      ref={formRef}
      requiredMark={false}
    >
      <div>
        <Form.Item
          name="formStart"
          rules={[
            {
              required: true,
              message: "Please select a form start"
            }
          ]}
        >
          <InputNumber
            placeholder="Start"
            min={1}
            max={100}
            onChange={(e) => setStart(e)}
          />
        </Form.Item>
        <Form.Item
          name="formEnd"
          rules={[
            {
              required: true,
              message: "Please select a form end"
            }
          ]}
        >
          <InputNumber
            placeholder="End"
            min={1}
            max={100}
            onChange={(e) => setEnd(e)}
          />
        </Form.Item>
        <Form.Item>
          <button htmlType="submit">Submit</button>
        </Form.Item>
      </div>
    </Form>
  );
};

If there is an alternative instead of using setState, It can also use ref (formRef.current)

Code sandbox: https://codesandbox.io/s/basic-usage-antd-4-21-0-forked-4sri66?file=/demo.js

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

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

发布评论

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

评论(2

我ぃ本無心為│何有愛 2025-02-13 17:01:04

对于自定义验证或有条件验证我们需要在我们的'valivator'中包含规则,如antd文档。

<Form.Item
      name="formEnd"
      rules={[
        {
          required: true,
          message: "Please select a form end"
        },
        ({ getFieldValue }) => ({
          validator(rule, value) {
            // from 'getFieldValue("fieldName")' we can get the current value of that field.
            if (value < getFieldValue("formStart")) {
              // value = currentValue of this field. with that we can do validations with other values in form fields
              return Promise.reject("End range must be greater than start"); // The validator should always return a promise on both success and error
            } else if (value === getFieldValue("formStart")) {
              return Promise.reject("End cannot be same as start");
            } else {
              return Promise.resolve();
            }
          }
        })
      ]}
    >

使用这种方法,您可以在不使用内部状态的情况下实现上述验证,也可以无需useref

使用ANTD表单时

  1. ANTD表单具有form.useform创建形式实例以维护数据存储的几点点。这样,我们可以轻松地获得当前的表单状态,例如值,错误等。
  2. 它还具有form.submit()函数,它触发了给定函数的onfinish。因此,我们可以将其用于提交BTN OnClick。

这是完整的

检查此 form/api 有关更多antd form prop and prop and函数。

For custom validations or conditional validations we need to include 'validator' inside our rules as below as per the antd docs.

<Form.Item
      name="formEnd"
      rules={[
        {
          required: true,
          message: "Please select a form end"
        },
        ({ getFieldValue }) => ({
          validator(rule, value) {
            // from 'getFieldValue("fieldName")' we can get the current value of that field.
            if (value < getFieldValue("formStart")) {
              // value = currentValue of this field. with that we can do validations with other values in form fields
              return Promise.reject("End range must be greater than start"); // The validator should always return a promise on both success and error
            } else if (value === getFieldValue("formStart")) {
              return Promise.reject("End cannot be same as start");
            } else {
              return Promise.resolve();
            }
          }
        })
      ]}
    >

With this approach, you can achieve above validation without use of internal state and also without useRef.

Few points for when use antd form

  1. antd form has Form.useForm which create Form instance to maintain data store. With this we can easily get the current form state like values, errors etc.
  2. It also has form.submit() function which trigger the given function for Form onFinish. So we can use that for SUBMIT Btn onClick.

Here is the full demo code in codesandbox.

Check this form/API for more antd Form props and functions.

何处潇湘 2025-02-13 17:01:04

您可以使用useref

import React, { useRef } from "react";

定义参考变量:

const start = useRef();
const end = useRef();

将refs传递给输入:

<InputNumber placeholder="Start" min={1} max={100} ref={start} />
<InputNumber placeholder="End" min={1} max={100} ref={end} />

访问输入值:

if (end.current.value < start.current.value) {
    // some code
}

您还可以通过添加defaultValue属性来设置默认值。例如:

<InputNumber placeholder="Start" min={1} max={100} ref={start} defaultValue={1} />

You can use useRef:

import React, { useRef } from "react";

Define ref variables:

const start = useRef();
const end = useRef();

Pass the refs to the inputs:

<InputNumber placeholder="Start" min={1} max={100} ref={start} />
<InputNumber placeholder="End" min={1} max={100} ref={end} />

Access the input values:

if (end.current.value < start.current.value) {
    // some code
}

You can also set the default values by adding the defaultValue attribute. For example:

<InputNumber placeholder="Start" min={1} max={100} ref={start} defaultValue={1} />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文