Skip to content

Commit bdcef30

Browse files
committed
perf: useValidator hooks
1 parent f8fdebf commit bdcef30

File tree

1 file changed

+29
-31
lines changed

1 file changed

+29
-31
lines changed

src/hooks/web/useValidator.ts

Lines changed: 29 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,60 @@
1-
const { t } = useI18n()
1+
import { useI18n } from '@/hooks/web/useI18n'
2+
import { FormItemRule } from 'element-plus'
23

3-
type Callback = (error?: string | Error | undefined) => void
4+
const { t } = useI18n()
45

56
interface LengthRange {
67
min: number
78
max: number
8-
message: string
9+
message?: string
910
}
1011

1112
export const useValidator = () => {
12-
const required = (message?: string) => {
13+
const required = (message?: string): FormItemRule => {
1314
return {
1415
required: true,
1516
message: message || t('common.required')
1617
}
1718
}
1819

19-
const lengthRange = (val: any, callback: Callback, options: LengthRange) => {
20+
const lengthRange = (options: LengthRange): FormItemRule => {
2021
const { min, max, message } = options
21-
if (val.length < min || val.length > max) {
22-
callback(new Error(message))
23-
} else {
24-
callback()
25-
}
26-
}
2722

28-
const notSpace = (val: any, callback: Callback, message: string) => {
29-
// 用户名不能有空格
30-
if (val.indexOf(' ') !== -1) {
31-
callback(new Error(message))
32-
} else {
33-
callback()
23+
return {
24+
min,
25+
max,
26+
message: message || t('common.lengthRange', { min, max })
3427
}
3528
}
3629

37-
const notSpecialCharacters = (val: any, callback: Callback, message: string) => {
38-
// 密码不能是特殊字符
39-
if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gi.test(val)) {
40-
callback(new Error(message))
41-
} else {
42-
callback()
30+
const notSpace = (message?: string): FormItemRule => {
31+
return {
32+
validator: (_, val, callback) => {
33+
if (val?.indexOf(' ') !== -1) {
34+
callback(new Error(message || t('common.notSpace')))
35+
} else {
36+
callback()
37+
}
38+
}
4339
}
4440
}
4541

46-
// 两个字符串是否想等
47-
const isEqual = (val1: string, val2: string, callback: Callback, message: string) => {
48-
if (val1 === val2) {
49-
callback()
50-
} else {
51-
callback(new Error(message))
42+
const notSpecialCharacters = (message?: string): FormItemRule => {
43+
return {
44+
validator: (_, val, callback) => {
45+
if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gi.test(val)) {
46+
callback(new Error(message || t('common.notSpecialCharacters')))
47+
} else {
48+
callback()
49+
}
50+
}
5251
}
5352
}
5453

5554
return {
5655
required,
5756
lengthRange,
5857
notSpace,
59-
notSpecialCharacters,
60-
isEqual
58+
notSpecialCharacters
6159
}
6260
}

0 commit comments

Comments
 (0)