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 import (
8 "reflect"
9 )
10 11 // ErrInInvalid is the error that returns in case of an invalid value for "in" rule.
12 var ErrInInvalid = NewError("validation_in_invalid", "must be a valid value")
13 14 // In returns a validation rule that checks if a value can be found in the given list of values.
15 // reflect.DeepEqual() will be used to determine if two values are equal.
16 // For more details please refer to https://golang.org/pkg/reflect/#DeepEqual
17 // An empty value is considered valid. Use the Required rule to make sure a value is not empty.
18 func In(values ...interface{}) InRule {
19 return InRule{
20 elements: values,
21 err: ErrInInvalid,
22 }
23 }
24 25 // InRule is a validation rule that validates if a value can be found in the given list of values.
26 type InRule struct {
27 elements []interface{}
28 err Error
29 }
30 31 // Validate checks if the given value is valid or not.
32 func (r InRule) Validate(value interface{}) error {
33 value, isNil := Indirect(value)
34 if isNil || IsEmpty(value) {
35 return nil
36 }
37 38 for _, e := range r.elements {
39 if reflect.DeepEqual(e, value) {
40 return nil
41 }
42 }
43 44 return r.err
45 }
46 47 // Error sets the error message for the rule.
48 func (r InRule) Error(message string) InRule {
49 r.err = r.err.SetMessage(message)
50 return r
51 }
52 53 // ErrorObject sets the error struct for the rule.
54 func (r InRule) ErrorObject(err Error) InRule {
55 r.err = err
56 return r
57 }
58