custom_rules.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package validators
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "github.com/runningwater/gohub/pkg/database"
  7. "github.com/thedevsaddam/govalidator"
  8. )
  9. func init() {
  10. // 自定义验证规则 not_exists, 用于验证数据不存在于数据库中
  11. // 常用于保证数据库某个字段的值唯一, 如用户名、邮箱、手机号或者分类的名称
  12. //
  13. // 用法示例
  14. //
  15. // 规则: not_exists:users,phone
  16. // 解释:验证 users 表中是否存在 phone 字段的值,phone 为待验证的值
  17. //
  18. // 规则: not_exists:users,phone,10
  19. // 解释:验证 users 表中是否存在 phone 字段的值,同时排除 id 为 10 的记录
  20. govalidator.AddCustomRule("not_exists", func(field string, rule string, message string, value any) error {
  21. rng := strings.Split(strings.TrimPrefix(rule, "not_exists:"), ",")
  22. // 第一个参数,表名称,如 users
  23. tableName := rng[0]
  24. // 第二个参数,字段名称,如 phone
  25. fieldName := rng[1]
  26. // 第三个参数,排除 ID
  27. var exceptID string
  28. if len(rng) > 2 {
  29. exceptID = rng[2]
  30. }
  31. // 用户请求的值
  32. requestValue := value.(string)
  33. // 调用数据库查询方法,检查数据是否存在
  34. query := database.DB.Table(tableName).Where(fieldName+" = ?", requestValue)
  35. if len(exceptID) > 0 {
  36. query.Where("id != ?", exceptID)
  37. }
  38. var count int64
  39. query.Count(&count)
  40. // 如果 count 大于 0,表示数据已存在,返回错误信息
  41. if count > 0 {
  42. // 如果有自定义错误消息的话,使用自定义错误消息
  43. if len(message) > 0 {
  44. return errors.New(message)
  45. }
  46. return fmt.Errorf("%v 已存在", requestValue)
  47. }
  48. return nil
  49. })
  50. }