常用类型及数据操作方法
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.2 KiB

3 years ago
  1. package helper
  2. import (
  3. "errors"
  4. "regexp"
  5. "strings"
  6. )
  7. /**
  8. * 验证
  9. * 2020/08/10
  10. */
  11. type Validate struct {
  12. Data []interface{}
  13. Title []string
  14. Rule []string //多个规则使用逗号(,)隔开
  15. }
  16. func (v *Validate) Check() error {
  17. if len(v.Data) == 0 {
  18. return nil
  19. }
  20. if len(v.Data) != len(v.Title) || len(v.Data) != len(v.Rule) {
  21. return errors.New("验证参数不对应")
  22. }
  23. msg := make([]string, 0)
  24. var ok bool
  25. for key, data := range v.Data {
  26. rules := strings.Split(v.Rule[key], ",") //分隔所有规则
  27. for _, rule := range rules {
  28. switch rule {
  29. case "require":
  30. ok = require(data)
  31. if !ok {
  32. msg = append(msg, StringJoin(v.Title[key], "不能为空"))
  33. }
  34. }
  35. }
  36. }
  37. if len(msg) == 0 {
  38. return nil
  39. }
  40. return errors.New(strings.Join(msg, ","))
  41. }
  42. func require(data interface{}) bool {
  43. if ToString(data) == "" {
  44. return false
  45. }
  46. return true
  47. }
  48. // 判断手机号码
  49. func IsMobile(mobile string) bool {
  50. result, _ := regexp.MatchString(`^(1[3|4|5|6|7|8]\d{9})$`, mobile)
  51. if result {
  52. return true
  53. } else {
  54. return false
  55. }
  56. }
  57. // 判断邮箱
  58. func IsEmail(email string) bool {
  59. pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱
  60. reg := regexp.MustCompile(pattern)
  61. return reg.MatchString(email)
  62. }