string.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 "errors"
  6. type stringValidator func(string) bool
  7. // StringRule is a rule that checks a string variable using a specified stringValidator.
  8. type StringRule struct {
  9. validate stringValidator
  10. message string
  11. }
  12. // NewStringRule creates a new validation rule using a function that takes a string value and returns a bool.
  13. // The rule returned will use the function to check if a given string or byte slice is valid or not.
  14. // An empty value is considered to be valid. Please use the Required rule to make sure a value is not empty.
  15. func NewStringRule(validator stringValidator, message string) *StringRule {
  16. return &StringRule{
  17. validate: validator,
  18. message: message,
  19. }
  20. }
  21. // Error sets the error message for the rule.
  22. func (v *StringRule) Error(message string) *StringRule {
  23. return NewStringRule(v.validate, message)
  24. }
  25. // Validate checks if the given value is valid or not.
  26. func (v *StringRule) Validate(value interface{}) error {
  27. value, isNil := Indirect(value)
  28. if isNil || IsEmpty(value) {
  29. return nil
  30. }
  31. str, err := EnsureString(value)
  32. if err != nil {
  33. return err
  34. }
  35. if v.validate(str) {
  36. return nil
  37. }
  38. return errors.New(v.message)
  39. }