跳到正文

好奇心改變世界

[ React+ant Design] ProFrom高级表单 - 基本的几种格式验证

582 2 分钟

antD 中常用的几种表单格式验证,用的 ProFrom 高级表单组件,主要看表单格式验证的部分,同 From 表单大同小异。

下面就是基本的几种格式验证:

1、不能为空

required: boolean 是否为必选字段

1
2
3
4
5
6
7
8
<ProFormText
name="title"
label="标题"
placeholder="请输入标题"
rules={[
{required: true, message: '标题不能为空'}
]}
/>

2、( pattern ) 正则表达式匹配,限制输入为数字

1
2
3
4
5
6
7
8
9
<ProFormText
name="order"
label="序号"
placeholder="请输入序号"
rules={[
{required: true, message: '序号不能为空'},
{pattern: /^[0-9]+$/,message: '序号只能输入数字'}
]}
/>

3、( max ) 限制字符长度

string 类型为字符串最大长度;number 类型时为最大值;array 类型时为数组最大长度

1
2
3
4
5
6
7
8
9
<ProFormText
name="brief"
label="摘要内容"
placeholder="请输入摘要内容"
rules={[
{required: true, message: '摘要内容不能为空'},
{max: 150,message: '摘要内容不能超过150个字符',}
]}
/>

4、( min ) 字符最小长度

string 类型为字符串最小长度;number 类型时为最小值;array 类型时为数组最小长度

1
2
3
4
5
6
7
8
9
<ProFormText
name="keyWord"
label="关键词"
placeholder="关键词"
rules={[
{required: true, message: '关键词不能为空'},
{min: 4,message: '关键词不能少于4个字符',}
]}
/>

5、( min、max ) 组合使用,限制字符长度范围

1
2
3
4
5
6
7
8
9
10
<ProFormText
name="creatPaper"
label="创建人"
placeholder="请输入创建人姓名"
rules={[
{required: true, message: '创建人姓名不能为空'},
{min: 2,message: '创建人姓名不能少于2个字符',},
{max: 20,message: '创建人姓名不能超过20个字符',}
]}
/>

6、( whitespace ) 组合使用,限制字符长度范围

whitespace: boolean 如果字段仅包含空格则校验不通过

1
2
3
4
5
6
7
8
9
<ProFormText
name="majors"
label="大学专业"
placeholder="请输入专业"
rules={[
{required: true, message: '专业不能为空'},
{whitespace: true,message: '仅输入空格无效'}
]}
/>

7、( validator ) 自定义校验

自定义校验,接收 Promise 作为返回值,(rule, value) => Promise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<ProFormText
name="creatPaper"
label="年龄"
placeholder="请输入年龄"
rules={[
{required: true, message: '年龄不能为空'},
{validator: numberCheck}
]}
/>
<script>
// 自定义校验,输入正整数,且大于0
const numberCheck = (rule, value, callback) => {
if (value % 1 !== 0 || value <= 0) {
callback('请输入正整数,且大于0')
}
callback(); // 必须返回一个callback
}
</script>

以上就是在 React ProFrom 高级表单中,经常用到的几种表单项格式验证了。


扫码关注