为什么数字验证规则在 antd 中不起作用 [英] Why number validate rule doesnt work in antd

查看:23
本文介绍了为什么数字验证规则在 antd 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的登录表单,但是输入项 tn 的 type: 'number' 验证规则不起作用.即使我输入一个数字,我也会在控制台中得到 'tn' is not a valid number' .

I have a simple login form, but validation rule with type: 'number' for input item tn doesn't work. Even if I enter a number, I get 'tn' is not a valid number' in console.

    import React from 'react';
    import { Form, Input, Button, Checkbox } from 'antd';
    import { UserOutlined, LockOutlined } from '@ant-design/icons';
    import './style.css';
    
    export const LoginForm = () => {
      const onFinish = (values) => {
        console.log('Received values of form: ', values);
      };
    
      return (
        <Form
          name="login_form"
          className="login-form"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
        >
          <h3 className="main-label">LOG IN</h3>
          <Form.Item
            name="tn"
            rules={[
              {
                type: 'number',
                required: true,
                message: 'Wrong number',
              },
            ]}
          >
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="Enter your tn"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: 'Please input your password',
              },
            ]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>Remember me</Checkbox>
            </Form.Item>
          </Form.Item>
    
         ...
      );
    };

我尝试了其他规则,它们运行良好.数字有什么问题?

I tried other rules and they works fine. What's the problem with numbers?

推荐答案

由于 Ant Design 的 <Input/> 组件,即使设置了类型属性,它也会将数字存储为字符串.

Due to Ant Design's <Input/> component, it will store the number as a string even if the type props have been set.

第一个解决方法是使用 Ant Design 的 组件,它不将数字存储为字符串(AFAIK 不查看源).尽管该组件相当不错,但它确实带有用于调整数字的箭头,如果提示诸如邮政编码之类的内容,这不是最佳选择.

The first workaround is to just use Ant Design's <Input Number/> component, which doesn't store the number as a string (AFAIK without looking at the source). Although that component is quite nice, it does come with the arrows for adjusting the number, which isn't optimal if prompting for something like a zip code.

经过进一步挖掘,无论是真正的错误还是疏忽,{type:number} 在使用 Ant Design 的 组件.

After further digging, whether it is a real bug or an overlook, {type:number} won't get you anywhere when using Ant Design's <Input/> component.

我建议您查看问题#731,然后查看问题#10003了解更多详情.(有一些非常简洁的验证代码,例如 this ...但只需浏览一下探索).

I would suggest you check out Issue #731, then check out Issue #10003 for more details. (there is some pretty neat validation code in both of those like this ... but just browse around and explore).

我喜欢只列出规则集而不实现自定义验证器的简单性(特别是对于像仅数字这样的问题);然而,这并不总是可能的.

I like the simplicity of just listing the rule sets without implementing a custom validator (especially for problems like number-only); however, it's not always possible.

这是我用于邮政编码验证的一些示例代码.请注意,您始终可以在验证器的末尾将消息字符串组合成一个 Promise.Reject(),但我发现它会使用户的屏幕变得混乱(尤其是有两个以上的验证错误消息).

Here is some sample code that I use for my Zip Code validation. Note that you could always combine the message strings into one Promise.Reject() at the end of the validator, but I find it clutters up the screen for the user (especially with more than two validation error messages).

<Form.Item
  validateTrigger="onBlur"
  name="ZipCode"
  label="Zip Code"
  hasFeedback
  rules={[
    {
      required: true,
      message: "Please enter zip code",
    },
    () => ({
      validator(_, value) {
        if (!value) {
          return Promise.reject();
        }
        if (isNaN(value)) {
          return Promise.reject("Zip code has to be a number.");
        }
        if (value.length < 5) {
          return Promise.reject("Zip code can't be less than 5 digits");
        }
        if (value.length > 5) {
          return Promise.reject("Zip code can't be more than 5 digits");
        }
        return Promise.resolve();
      },
    }),
  ]}
>
  <Input />
</Form.Item>;

不确定我是否只是忽略了这一点,或者他们是否最近提出了这一点,但是有一个使用自定义验证的有效输入(如您所愿).我相信这个 CodePen解决您的问题.

Not exactly sure if I just overlooked this or if they recently put it up, but there is a working input (like you want) using custom validation. I believe this CodePen will solve your problem.

这篇关于为什么数字验证规则在 antd 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆