UNPKG

create-base-teek-theme

Version:

``` npm create base-teek-theme@latest my-first-blog ```

121 lines (100 loc) 3.02 kB
--- date: 2025-07-02 11:59:46 title: 正则校验 permalink: /pages/d22904 author: name: 华总 link: https://xiaoying.org.cn categories: - 组件 --- ## 安装 ::: code-group ``` sh [npm] npm install regular-plus -D ``` ```sh [yarn] yarn add regular-plus -D ``` ```sh [pnpm] pnpm add regular-plus -D ``` ::: ## 使用 ### 正则校验 ```sh import regular from 'regular-plus'; console.log(regular.email.test('someemail@gmail.com')) // outputs true ``` ### 可用校验 ```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; // 文件拓展名的校验 ``` ## 自定义文件扩展名校验 ### 默认可用类型 ```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'], }; ``` ### 扩展 FileType 可以通过 TypeScript 的联合类型扩展 FileType ```ts import type { FileType } from 'regular-plus'; type MyFileType = FileType | 'video' | 'audio'; ``` ### 扩展 fileTypeExtMap 可以通过对象合并扩展 fileTypeExtMap ``` ts import { fileTypeExtMap } from 'your-npm-package'; const myFileTypeExtMap = { ...fileTypeExtMap, video: ['mp4', 'avi', 'mov'], audio: ['mp3', 'wav'], }; ``` ### 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> ```