ANTD打印2个错误,用于使用预定义规则的自定义验证器

发布于 2025-01-21 08:10:57 字数 1783 浏览 2 评论 0原文

我正在使用ReactJ中的ANTD文本区域,并且具有一些预定义的规则,如:

    const validationRules = [
        {
            required: true,
            message: 'Required',
        },
        {
            min: MIN_LENGTH,
            message: `min ${MIN_LENGTH} characters required`,
        },
    ];

形式项目如下:

<Form.Item name="myField" rules={validationRules}>
  <TextArea
    className="mt-32"   
    rows={6}
    placeholder={`Your answer should be between ${MIN_LENGTH} to ${MAX_LENGTH} characters`}
    minLength={MIN_LENGTH}
    maxLength={MAX_LENGTH}
    value={value}
  />
</Form.Item>;

现在要添加自定义验证规则,即如果用户进入2个以上的尾部空间,请警告他。

为此,我创建了一个自定义验证器AS:

async function validateEmptySpaces(rule: any, inputValue: string) {
  const trimmedValue = inputValue.trim();
  const diffInLength = inputValue.length - trimmedValue.length;
  if (diffInLength > 1) {
    throw new Error("remove empty spaces");
  }
}

因此,我最终将此验证器添加到MU规则中,为:

const validationRules = [
  {
    required: true,
    message: "Required",
  },
  {
    min: MIN_LENGTH,
    message: `min ${MIN_LENGTH} characters required`,
  },
  { validator: validateEmptySpaces },
];

现在,这就是我在UI中看到的方式

在这里,一次不是1个错误,它显示了两个错误。我该如何一次仅显示一条错误消息,例如:

I am using an antd text area in reactjs, and have some predefined rules as :

    const validationRules = [
        {
            required: true,
            message: 'Required',
        },
        {
            min: MIN_LENGTH,
            message: `min ${MIN_LENGTH} characters required`,
        },
    ];

Form Item is as follows:

<Form.Item name="myField" rules={validationRules}>
  <TextArea
    className="mt-32"   
    rows={6}
    placeholder={`Your answer should be between ${MIN_LENGTH} to ${MAX_LENGTH} characters`}
    minLength={MIN_LENGTH}
    maxLength={MAX_LENGTH}
    value={value}
  />
</Form.Item>;

Now want to add a custom validation rule i.e. to warn user if he enters more than 2 tailing spaces.
For this I have created a custom validator as:

async function validateEmptySpaces(rule: any, inputValue: string) {
  const trimmedValue = inputValue.trim();
  const diffInLength = inputValue.length - trimmedValue.length;
  if (diffInLength > 1) {
    throw new Error("remove empty spaces");
  }
}

So I add this validator to mu rules at the end as :

const validationRules = [
  {
    required: true,
    message: "Required",
  },
  {
    min: MIN_LENGTH,
    message: `min ${MIN_LENGTH} characters required`,
  },
  { validator: validateEmptySpaces },
];

Now this is How I get to see in UI
enter image description here

Here instead of 1 error at a time, it shows both the errors. How can I make it show only one error message at once like:
enter image description here

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文