1 // Copyright 2018 Qiang Xue, Google LLC. 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 // ErrNotInInvalid is the error that returns when a value is in a list.
8 var ErrNotInInvalid = NewError("validation_not_in_invalid", "must not be in list")
9 10 // NotIn returns a validation rule that checks if a value is absent from the given list of values.
11 // Note that the value being checked and the possible range of values must be of the same type.
12 // An empty value is considered valid. Use the Required rule to make sure a value is not empty.
13 func NotIn(values ...interface{}) NotInRule {
14 return NotInRule{
15 elements: values,
16 err: ErrNotInInvalid,
17 }
18 }
19 20 // NotInRule is a validation rule that checks if a value is absent from the given list of values.
21 type NotInRule struct {
22 elements []interface{}
23 err Error
24 }
25 26 // Validate checks if the given value is valid or not.
27 func (r NotInRule) Validate(value interface{}) error {
28 value, isNil := Indirect(value)
29 if isNil || IsEmpty(value) {
30 return nil
31 }
32 33 for _, e := range r.elements {
34 if e == value {
35 return r.err
36 }
37 }
38 return nil
39 }
40 41 // Error sets the error message for the rule.
42 func (r NotInRule) Error(message string) NotInRule {
43 r.err = r.err.SetMessage(message)
44 return r
45 }
46 47 // ErrorObject sets the error struct for the rule.
48 func (r NotInRule) ErrorObject(err Error) NotInRule {
49 r.err = err
50 return r
51 }
52