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 5 package validation
6 7 // ErrNotNilRequired is the error that returns when a value is Nil.
8 var ErrNotNilRequired = NewError("validation_not_nil_required", "is required")
9 10 // NotNil is a validation rule that checks if a value is not nil.
11 // NotNil only handles types including interface, pointer, slice, and map.
12 // All other types are considered valid.
13 var NotNil = notNilRule{}
14 15 type notNilRule struct {
16 err Error
17 }
18 19 // Validate checks if the given value is valid or not.
20 func (r notNilRule) Validate(value interface{}) error {
21 _, isNil := Indirect(value)
22 if isNil {
23 if r.err != nil {
24 return r.err
25 }
26 return ErrNotNilRequired
27 }
28 return nil
29 }
30 31 // Error sets the error message for the rule.
32 func (r notNilRule) Error(message string) notNilRule {
33 if r.err == nil {
34 r.err = ErrNotNilRequired
35 }
36 r.err = r.err.SetMessage(message)
37 return r
38 }
39 40 // ErrorObject sets the error struct for the rule.
41 func (r notNilRule) ErrorObject(err Error) notNilRule {
42 r.err = err
43 return r
44 }
45