useValidator.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { useI18n } from '@/hooks/web/useI18n'
  2. import { FormItemRule } from 'element-plus'
  3. const { t } = useI18n()
  4. interface LengthRange {
  5. min: number
  6. max: number
  7. message?: string
  8. }
  9. export const useValidator = () => {
  10. const required = (message?: string): FormItemRule => {
  11. return {
  12. required: true,
  13. message: message || t('common.required')
  14. }
  15. }
  16. const lengthRange = (options: LengthRange): FormItemRule => {
  17. const { min, max, message } = options
  18. return {
  19. min,
  20. max,
  21. message: message || t('common.lengthRange', { min, max })
  22. }
  23. }
  24. const notSpace = (message?: string): FormItemRule => {
  25. return {
  26. validator: (_, val, callback) => {
  27. if (val.indexOf(' ') !== -1) {
  28. callback(new Error(message || t('common.notSpace')))
  29. } else {
  30. callback()
  31. }
  32. }
  33. }
  34. }
  35. const notSpecialCharacters = (message?: string): FormItemRule => {
  36. return {
  37. validator: (_, val, callback) => {
  38. if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gi.test(val)) {
  39. callback(new Error(message || t('common.notSpecialCharacters')))
  40. } else {
  41. callback()
  42. }
  43. }
  44. }
  45. }
  46. return {
  47. required,
  48. lengthRange,
  49. notSpace,
  50. notSpecialCharacters
  51. }
  52. }