validateInputHandle.ets
2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* 手机号和密码的正则表达式 API
* @param input : 用户输入的手机号或者密码或者用户名
* @param type : 调用者需要明确传入的是手机号 还是 密码 校验
*/
type typeValue = "phone" | "password" | "email" | "idCard" | "businessLicenseNo" | "username"
export function ValidateInputHandle(input: string, type: typeValue): boolean {
switch(type) {
case "phone":
const phoneRegex = /^1[3456789]\d{9}$/
return phoneRegex.test(input)
case "email":
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(com|cn|net|org|edu|gov|io|co)$/;
return emailRegex.test(input)
case "businessLicenseNo":
const businessLicenseNoRegex = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/
return businessLicenseNoRegex.test(input)
case "username":
const usernameRegex = /^[a-zA-Z0-9]{4,20}$/
return usernameRegex.test(input)
case "idCard":
if(input === '') {
return true
} else {
const idCardRegex = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
return idCardRegex.test(input)
}
default :
throw new Error("传入的参数有误!")
}
}
// 校验函数
export function ValidateHandle(arr: string[], obj: Record<string, (string | number | null)>): boolean {
let keyArr: string[] = Object.keys(obj)
let valueArr = Object.values(obj) as (string | number | null )[]
for(let i = 0; i < keyArr.length; i++) {
console.log(keyArr[i], valueArr[i])
if(arr.includes(keyArr[i]) && valueArr[i] === '') return false
}
return true
}
interface objType {
username: string;
password: string;
phone: string;
email: string;
businessLicenseNo: string;
idCard: number;
}
let arrNew = ['username', 'password', 'phone', 'email', 'businessLicenseNo', 'idCard']
let objNew: objType = {
username: '',
password: '',
phone: '',
email: '',
businessLicenseNo: '',
idCard: 1234
}