tzi*_*zi0 5 javascript reactjs antd
我有一个简单的登录表单,但type: 'number'输入项 tn 的验证规则不起作用。即使我输入一个数字,我也会'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>
...
);
};
Run Code Online (Sandbox Code Playgroud)
我尝试了其他规则,它们工作得很好。数字有什么问题?
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>
Run Code Online (Sandbox Code Playgroud)
It's also worth noting that the getFieldDecorator() method is basically redundant as of v4 of Ant Design. They should also better advertise that.
The above Regex pattern enforces integers and disallows decimals.
由于 Ant Design 的<Input/>组件,即使已经设置了 type 属性,它也会将数字存储为字符串。
第一个解决方法是仅使用 Ant Design 的<Input Number/>组件,该组件不会将数字存储为字符串(据我所知,无需查看源代码)。尽管该组件非常好,但它确实带有用于调整数字的箭头,如果提示输入邮政编码等内容,这并不是最佳选择。
经过进一步挖掘,无论是真正的错误还是疏忽,{type:number}在使用 Ant Design 的组件时都不会给你带来任何帮助<Input/>。
我建议您查看Issue #731,然后查看Issue #10003了解更多详细信息。(在这两个代码中都有一些非常简洁的验证代码......但只需浏览并探索)。
我喜欢只列出规则集而不实现自定义验证器的简单性(特别是对于仅数字之类的问题);然而,这并不总是可能的。
这是我用于邮政编码验证的一些示例代码。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>;
Run Code Online (Sandbox Code Playgroud)
编辑:不太确定我是否只是忽略了这一点还是他们最近把它提出来了,但是有一个使用自定义验证的工作输入(如您想要的)。我相信这个CodePen会解决你的问题。
| 归档时间: |
|
| 查看次数: |
15196 次 |
| 最近记录: |