rule_match.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package valid
  2. import "regexp"
  3. // ErrMatchInvalid is the error that returns in case of invalid format.
  4. var ErrMatchInvalid = NewError("validation_match_invalid", "must be in a valid format")
  5. // Match returns a validation rule that checks if a value matches the specified regular expression.
  6. // This rule should only be used for validating strings and byte slices, or a validation error will be reported.
  7. // An empty value is considered valid. Use the Required rule to make sure a value is not empty.
  8. func Match(re *regexp.Regexp) MatchRule {
  9. return MatchRule{
  10. re: re,
  11. err: ErrMatchInvalid,
  12. }
  13. }
  14. // MatchRule is a validation rule that checks if a value matches the specified regular expression.
  15. type MatchRule struct {
  16. re *regexp.Regexp
  17. err Error
  18. }
  19. // Validate checks if the given value is valid or not.
  20. func (r MatchRule) Validate(value interface{}) error {
  21. value, isNil := Indirect(value)
  22. if isNil {
  23. return nil
  24. }
  25. isString, str, isBytes, bs := StringOrBytes(value)
  26. if isString && (str == "" || r.re.MatchString(str)) {
  27. return nil
  28. } else if isBytes && (len(bs) == 0 || r.re.Match(bs)) {
  29. return nil
  30. }
  31. return r.err
  32. }
  33. // Error sets the error message for the rule.
  34. func (r MatchRule) Error(message string) MatchRule {
  35. r.err = r.err.SetMessage(message)
  36. return r
  37. }
  38. // ErrorObject sets the error struct for the rule.
  39. func (r MatchRule) ErrorObject(err Error) MatchRule {
  40. r.err = err
  41. return r
  42. }