useValidator.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. const isEmail = (message: string): FormItemRule => {
  47. return {
  48. validator: (_, val, callback) => {
  49. // 判断是否是邮箱
  50. if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/g.test(val)) {
  51. callback(new Error(message))
  52. } else {
  53. callback()
  54. }
  55. }
  56. }
  57. }
  58. const isMobilePhone = (message: string): FormItemRule => {
  59. return {
  60. validator: (_, val, callback) => {
  61. // 判断是否是手机号
  62. if (
  63. !/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/g.test(val)
  64. ) {
  65. callback(new Error(message))
  66. } else {
  67. callback()
  68. }
  69. }
  70. }
  71. }
  72. return {
  73. required,
  74. lengthRange,
  75. notSpace,
  76. notSpecialCharacters,
  77. isEmail,
  78. isMobilePhone
  79. }
  80. }