# antd中form表单验证
**Repository Path**: hope93/antd-form2
## Basic Information
- **Project Name**: antd中form表单验证
- **Description**: antd中form表单(2):格式验证和限制
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 4
- **Forks**: 2
- **Created**: 2018-11-09
- **Last Updated**: 2021-11-23
## Categories & Tags
**Categories**: Uncategorized
**Tags**: 奥利给
## README
# antd中form表单验证
## 格式限制
antd中表单的功能很多,下面就为大家整理了一下antd中常用的几种表单输入格式验证:
**1. 输入框不能为空限制,如下:**
```
{getFieldDecorator('name', {
rules: [{
required: true,
message: '名称不能为空',
}],
})(
)}
```
**2. 输入框字符限制,如下:**
**字符长度范围限制:**
```
{getFieldDecorator('password', {
rules: [{
required: true,
message: '密码不能为空',
}, {
min:4,
message: '密码不能少于4个字符',
}, {
max:6,
message: '密码不能大于6个字符',
}],
})(
)}
```
**字符长度限制:**
```
{getFieldDecorator('nickname', {
rules: [{
required: true,
message: '昵称不能为空',
}, {
len: 4,
message: '长度需4个字符',
}],
})(
)}
```
**3. 自定义校验**
```
{getFieldDecorator('passwordcomfire', {
rules: [{
required: true,
message: '请再次输入密码',
}, {
validator: passwordValidator
}],
})(
)}
// 密码验证
const passwordValidator = (rule, value, callback) => {
const { getFieldValue } = form;
if (value && value !== getFieldValue('password')) {
callback('两次输入不一致!')
}
// 必须总是返回一个 callback,否则 validateFields 无法响应
callback();
}
```
validator属性自定义效验,必须返回一个callback
**4.whitespace空格报错**
```
{getFieldDecorator('hobody', {
rules: [{
whitespace: true,
message: '不能输入空格',
} ],
})(
)}
```
若输入只有一个空格,则会报错
**5.pattern正则验证**
```
{getFieldDecorator('qbc', {
rules: [{
message:'只能输入数字',
pattern: /^[0-9]+$/
} ],
})(
)}
```
如果输入的不是数字,则提示错误
完整代码地址:
https://gitee.com/hope93/antd-form2