checker.go 733 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package checker
  2. import (
  3. "regexp"
  4. "strings"
  5. )
  6. type Type byte
  7. const (
  8. Undefined Type = iota
  9. Email
  10. Phone
  11. )
  12. func (s Type) String() string {
  13. switch s {
  14. case Email:
  15. return "email"
  16. case Phone:
  17. return "phone"
  18. default:
  19. return "undefined"
  20. }
  21. }
  22. var (
  23. checkers = map[Type]*regexp.Regexp{
  24. Email: regexp.MustCompile("^.*?@.*?\\.[\\w]+$"),
  25. Phone: regexp.MustCompile("^\\+\\d{11}$"),
  26. }
  27. )
  28. func Check(source string) Type {
  29. source = strings.TrimSpace(source)
  30. for i, v := range checkers {
  31. if v.MatchString(source) {
  32. return i
  33. }
  34. }
  35. return Undefined
  36. }
  37. func CheckEmail(email string) bool {
  38. return checkers[Email].MatchString(email)
  39. }
  40. func CheckPhone(phone string) bool {
  41. return checkers[Phone].MatchString(phone)
  42. }