rule_strings.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package valid
  2. var (
  3. // ErrBlankString is the error that returns when a value is an empty string/only whitespaces.
  4. ErrBlankString = NewError("validation_required", "cannot be blank")
  5. )
  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. err Error
  11. denyBlank bool
  12. }
  13. // NewStringRule creates a new validation rule using a function that takes a string value and returns a bool.
  14. // The rule returned will use the function to check if a given string or byte slice is valid or not.
  15. // An empty value is considered to be valid. Please use the Required rule to make sure a value is not empty.
  16. func NewStringRule(allowBlank bool, validator stringValidator, message string) StringRule {
  17. return StringRule{
  18. validate: validator,
  19. err: NewError("", message),
  20. denyBlank: !allowBlank,
  21. }
  22. }
  23. // NewStringRuleWithError creates a new validation rule using a function that takes a string value and returns a bool.
  24. // The rule returned will use the function to check if a given string or byte slice is valid or not.
  25. // An empty value is considered to be valid. Please use the Required rule to make sure a value is not empty.
  26. func NewStringRuleWithError(validator stringValidator, err Error) StringRule {
  27. return StringRule{
  28. validate: validator,
  29. err: err,
  30. }
  31. }
  32. // Error sets the error message for the rule.
  33. func (r StringRule) Error(message string) StringRule {
  34. r.err = r.err.SetMessage(message)
  35. return r
  36. }
  37. // ErrorObject sets the error struct for the rule.
  38. func (r StringRule) ErrorObject(err Error) StringRule {
  39. r.err = err
  40. return r
  41. }
  42. // Validate checks if the given value is valid or not.
  43. func (r StringRule) Validate(value interface{}) error {
  44. value, isNil := Indirect(value)
  45. if isNil {
  46. return nil
  47. }
  48. str, err := EnsureString(value)
  49. if err != nil {
  50. return err
  51. }
  52. if r.denyBlank && IsEmpty(value) {
  53. return nil
  54. }
  55. if !r.denyBlank {
  56. if IsEmpty(value) {
  57. return nil
  58. }
  59. } else {
  60. if IsBlankString(str) {
  61. return ErrBlankString
  62. }
  63. }
  64. if r.validate(str) {
  65. return nil
  66. }
  67. return r.err
  68. }