简体   繁体   English

为什么数字验证规则在 antd 中不起作用

[英]Why number validate rule doesnt work in antd

I have a simple login form, but validation rule with type: 'number' for input item tn doesn't work.我有一个简单的登录表单,但输入项 tn type: 'number'的验证规则不起作用。 Even if I enter a number, I get 'tn' is not a valid number' in console.即使我输入一个数字,我也会在控制台中得到'tn' is not a valid number'

    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?数字有什么问题?

The built in method does not work as Ant Design v4 recognises inputs as string.内置方法不起作用,因为 Ant Design v4 将输入识别为字符串。 The solution is to use Regex.解决方案是使用正则表达式。

<Form.Item
    name="myNumber"
    rules={[{ 
        required: true, 
        message: "A value must be entered",
        pattern: new RegExp(/^[0-9]+$/)
    }]}
>
    <Input
        placeholder="x"
        maxLength={5}
    />
</Form.Item>

It's also worth noting that the getFieldDecorator() method is basically redundant as of v4 of Ant Design.还值得注意的是getFieldDecorator()方法从 Ant Design 的 v4 开始基本上是多余的。 They should also better advertise that.他们还应该更好地宣传这一点。

The above Regex pattern enforces integers and disallows decimals.上面的 Regex 模式强制使用整数并不允许使用小数。

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 的<Input/>组件,即使设置了类型道具,它也会将数字存储为字符串。

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).第一个解决方法是只使用 Ant Design 的<Input Number/>组件,它不会将数字存储为字符串(AFAIK 不查看源代码)。 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.尽管该组件非常好,但它确实带有用于调整数字的箭头,如果提示输入 zip 代码之类的东西,这并不是最佳选择。

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.经过进一步挖掘,无论是真正的错误还是忽略,在使用 Ant Design 的<Input/>组件时, {type:number}都不会让您有任何收获。

I would suggest you check out Issue #731 , then check out Issue #10003 for more details.我建议您查看问题 #731 ,然后查看问题 #10003了解更多详细信息。 (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.然而,这并不总是可能的。

Here is some sample code that I use for my Zip Code validation.这是我用于 Zip 代码验证的一些示例代码。 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).请注意,您始终可以在验证器末尾将消息字符串组合成一个Promise.Reject() ,但我发现它会使用户的屏幕变得混乱(尤其是有两个以上的验证错误消息)。

<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>;

Edit: 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.我相信这个CodePen会解决你的问题。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM