Appearance
正则校验
安装
sh
npm install regular-plus -D
1
sh
yarn add regular-plus -D
1
sh
pnpm add regular-plus -D
1
使用
正则校验
sh
import regular from 'regular-plus';
console.log(regular.email.test('someemail@gmail.com')) // outputs true
1
2
3
2
3
可用校验
sh
email: RegExp; // 邮箱地址
url: RegExp; // URL地址
domain: RegExp; // 域名
ipv4: RegExp; // IPv4地址
creditCard: RegExp; // 信用卡号
slug: RegExp; // 全部由小写字母(a-z)、数字(0-9)、或 - 构成且不能有空格、下划线、大写字母、中文、特殊符号等
number: RegExp; // 正整数数字字符串
html: RegExp; // HTML标签匹配,
phone: RegExp; // 手机号码
sfzReg: RegExp; // 身份证号码
hexcolor: RegExp; // 十六进制颜色
date: RegExp; // 日期格式 YYYY-MM-DD
dateReg: RegExp; // 日期时间格式 YYYY-MM-DD HH:mm:ss
int: RegExp; // 整数
float: RegExp; // 浮点数
post: RegExp; // 邮政编码
qqReg: RegExp; // QQ号
wxReg: RegExp; // 微信号
carNoReg: RegExp; // 车牌号
password: RegExp; // 密码,至少8位,包含大小写字母和数字
fileExt: RegExp; // 文件拓展名的校验
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
自定义文件扩展名校验
默认可用类型
ts
type FileType = 'image' | 'doc' | 'archive';
const fileTypeExtMap: Record<FileType, string[]> = {
image: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'],
doc: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'md'],
archive: ['zip', 'rar'],
};
1
2
3
4
5
6
7
2
3
4
5
6
7
扩展 FileType
可以通过 TypeScript 的联合类型扩展 FileType
ts
import type { FileType } from 'regular-plus';
type MyFileType = FileType | 'video' | 'audio';
1
2
3
2
3
扩展 fileTypeExtMap
可以通过对象合并扩展 fileTypeExtMap
ts
import { fileTypeExtMap } from 'your-npm-package';
const myFileTypeExtMap = {
...fileTypeExtMap,
video: ['mp4', 'avi', 'mov'],
audio: ['mp3', 'wav'],
};
1
2
3
4
5
6
7
2
3
4
5
6
7
Vue + Element Plus 上传校验集成示例
vue
<template>
<el-upload :before-upload="beforeUpload">
<el-button>上传文件</el-button>
</el-upload>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus';
import type { FileType } from 'regular-plus';
import { isAllowedFileType, getAllowedExtensions, fileTypeExtMap } from "regular-plus"
const allowedTypes: MyFileType[] = ['image', 'doc'];
function beforeUpload(file: File): boolean {
if (!isAllowedFileType(file.name, allowedTypes, myFileTypeExtMap)) {
const extText = getAllowedExtensions(allowedTypes, myFileTypeExtMap).join(', ');
ElMessage.error(`只允许上传以下类型的文件:${extText}`);
return false;
}
return true;
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23