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

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

问题描述

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

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 v4将输入识别为字符串,因此内置方法不起作用.解决方案是使用正则表达式.

The built in method does not work as Ant Design v4 recognises inputs as string. 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>

值得注意的是,从Ant Design v4开始, getFieldDecorator()方法基本上是多余的.他们还应该更好地做广告.

It's also worth noting that the getFieldDecorator() method is basically redundant as of v4 of Ant Design. They should also better advertise that.

上面的Regex模式强制使用整数,而不允许使用小数.

The above Regex pattern enforces integers and disallows decimals.

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

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