match.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2016 Qiang Xue. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package validation
  5. import (
  6. "errors"
  7. "regexp"
  8. )
  9. // Match returns a validation rule that checks if a value matches the specified regular expression.
  10. // This rule should only be used for validating strings and byte slices, or a validation error will be reported.
  11. // An empty value is considered valid. Use the Required rule to make sure a value is not empty.
  12. func Match(re *regexp.Regexp) *MatchRule {
  13. return &MatchRule{
  14. re: re,
  15. message: "must be in a valid format",
  16. }
  17. }
  18. type MatchRule struct {
  19. re *regexp.Regexp
  20. message string
  21. }
  22. // Validate checks if the given value is valid or not.
  23. func (v *MatchRule) Validate(value interface{}) error {
  24. value, isNil := Indirect(value)
  25. if isNil {
  26. return nil
  27. }
  28. isString, str, isBytes, bs := StringOrBytes(value)
  29. if isString && (str == "" || v.re.MatchString(str)) {
  30. return nil
  31. } else if isBytes && (len(bs) == 0 || v.re.Match(bs)) {
  32. return nil
  33. }
  34. return errors.New(v.message)
  35. }
  36. // Error sets the error message for the rule.
  37. func (v *MatchRule) Error(message string) *MatchRule {
  38. v.message = message
  39. return v
  40. }