12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- package valid
- var (
-
- ErrBlankString = NewError("validation_required", "cannot be blank")
- )
- type stringValidator func(string) bool
- type StringRule struct {
- validate stringValidator
- err Error
- denyBlank bool
- }
- func NewStringRule(allowBlank bool, validator stringValidator, message string) StringRule {
- return StringRule{
- validate: validator,
- err: NewError("", message),
- denyBlank: !allowBlank,
- }
- }
- func NewStringRuleWithError(validator stringValidator, err Error) StringRule {
- return StringRule{
- validate: validator,
- err: err,
- }
- }
- func (r StringRule) Error(message string) StringRule {
- r.err = r.err.SetMessage(message)
- return r
- }
- func (r StringRule) ErrorObject(err Error) StringRule {
- r.err = err
- return r
- }
- func (r StringRule) Validate(value interface{}) error {
- value, isNil := Indirect(value)
- if isNil {
- return nil
- }
- str, err := EnsureString(value)
- if err != nil {
- return err
- }
- if r.denyBlank && IsEmpty(value) {
- return nil
- }
- if !r.denyBlank {
- if IsEmpty(value) {
- return nil
- }
- } else {
- if IsBlankString(str) {
- return ErrBlankString
- }
- }
- if r.validate(str) {
- return nil
- }
- return r.err
- }
|