verify_code_request.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package requests
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/runningwater/gohub/pkg/captcha"
  5. "github.com/thedevsaddam/govalidator"
  6. )
  7. type VerifyCodeRequest struct {
  8. Phone string `json:"phone,omitempy" valid:"phone"`
  9. CaptchaID string `json:"captcha_id,omitempy" valid:"captcha_id"`
  10. CaptchaAnswer string `json:"captcha_answer,omitempy" valid:"captcha_answer"`
  11. }
  12. func VerifyCodePhone(data any, c *gin.Context) map[string][]string {
  13. // 1. 定制认证规则
  14. rules := govalidator.MapData{
  15. "phone": []string{"required", "digits:11"},
  16. "captcha_id": []string{"required"},
  17. "captcha_answer": []string{"required", "digits:6"},
  18. }
  19. // 2. 定制错误信息
  20. messages := govalidator.MapData{
  21. "phone": []string{
  22. "required:手机号不能为空",
  23. "digits:手机号格式不正确,长度必须为11位",
  24. },
  25. "captcha_id": []string{
  26. "required:验证码ID不能为空",
  27. },
  28. "captcha_answer": []string{
  29. "required:验证码不能为空",
  30. "digits:验证码格式不正确,长度必须为6位",
  31. },
  32. }
  33. errs := validate(data, rules, messages)
  34. // Captcha 图片验证
  35. _data := data.(*VerifyCodeRequest)
  36. if ok := captcha.NewCaptcha().VerifyCaptcha(_data.CaptchaID, _data.CaptchaAnswer); !ok {
  37. errs["captcha_answer"] = append(errs["captcha_answer"], "验证码错误")
  38. }
  39. // 3. 返回错误信息
  40. return errs
  41. }