validate.uts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * 表单验证工具
  3. */
  4. /**
  5. * 验证手机号
  6. */
  7. export const validatePhone = (phone: string): boolean => {
  8. const phoneReg = /^1[3-9]\d{9}$/
  9. return phoneReg.test(phone)
  10. }
  11. /**
  12. * 验证邮箱
  13. */
  14. export const validateEmail = (email: string): boolean => {
  15. const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  16. return emailReg.test(email)
  17. }
  18. /**
  19. * 验证身份证号
  20. */
  21. export const validateIdCard = (idCard: string): boolean => {
  22. const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  23. return idCardReg.test(idCard)
  24. }
  25. /**
  26. * 验证密码强度
  27. * 必须包含:数字、大小写字母、特殊字符,长度至少6位
  28. */
  29. export const validatePassword = (password: string): boolean => {
  30. // 长度至少6位
  31. if (password.length < 6) {
  32. return false
  33. }
  34. // 必须包含数字
  35. const hasNumber = /[0-9]/.test(password)
  36. // 必须包含小写字母
  37. const hasLowerCase = /[a-z]/.test(password)
  38. // 必须包含大写字母
  39. const hasUpperCase = /[A-Z]/.test(password)
  40. // 必须包含特殊字符
  41. const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)
  42. return hasNumber && hasLowerCase && hasUpperCase && hasSpecialChar
  43. }
  44. /**
  45. * 验证是否为空
  46. */
  47. export const validateRequired = (value: string): boolean => {
  48. return value != null && value.trim().length > 0
  49. }
  50. /**
  51. * 验证数字
  52. */
  53. export const validateNumber = (value: string): boolean => {
  54. const numberReg = /^[0-9]+(\.[0-9]+)?$/
  55. return numberReg.test(value)
  56. }
  57. /**
  58. * 验证整数
  59. */
  60. export const validateInteger = (value: string): boolean => {
  61. const integerReg = /^[0-9]+$/
  62. return integerReg.test(value)
  63. }
  64. /**
  65. * 验证字符串长度范围
  66. */
  67. export const validateLength = (value: string, min: number, max: number): boolean => {
  68. const length = value.length
  69. return length >= min && length <= max
  70. }
  71. /**
  72. * 验证 URL
  73. */
  74. export const validateUrl = (url: string): boolean => {
  75. const urlReg = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
  76. return urlReg.test(url)
  77. }