Files
ipms-sjy-ui/src/hooks/web/useValidator.ts

61 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-10-31 10:11:43 +08:00
import { useI18n } from '@/hooks/web/useI18n'
import { FormItemRule } from 'element-plus'
2023-10-31 10:11:43 +08:00
const { t } = useI18n()
interface LengthRange {
min: number
max: number
2023-10-31 10:11:43 +08:00
message?: string
}
export const useValidator = () => {
2023-10-31 10:11:43 +08:00
const required = (message?: string): FormItemRule => {
return {
required: true,
message: message || t('common.required')
}
}
2023-10-31 10:11:43 +08:00
const lengthRange = (options: LengthRange): FormItemRule => {
const { min, max, message } = options
2023-10-31 10:11:43 +08:00
return {
min,
max,
message: message || t('common.lengthRange', { min, max })
}
}
2023-10-31 10:11:43 +08:00
const notSpace = (message?: string): FormItemRule => {
return {
validator: (_, val, callback) => {
if (val?.indexOf(' ') !== -1) {
callback(new Error(message || t('common.notSpace')))
} else {
callback()
}
}
}
}
2023-10-31 10:11:43 +08:00
const notSpecialCharacters = (message?: string): FormItemRule => {
return {
validator: (_, val, callback) => {
if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gi.test(val)) {
callback(new Error(message || t('common.notSpecialCharacters')))
} else {
callback()
}
}
}
}
return {
required,
lengthRange,
notSpace,
2023-10-31 10:11:43 +08:00
notSpecialCharacters
}
}