Skip to content

Commit 027affc

Browse files
committed
add len,min,max,regex... support for pointer type
1 parent 0a9835d commit 027affc

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

builtins.go

+26-1
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,12 @@ func nonzero(v interface{}, param string) error {
6262
func length(v interface{}, param string) error {
6363
st := reflect.ValueOf(v)
6464
valid := true
65+
if st.Kind() == reflect.Ptr {
66+
if st.IsNil() {
67+
return nil
68+
}
69+
st = st.Elem()
70+
}
6571
switch st.Kind() {
6672
case reflect.String:
6773
p, err := asInt(param)
@@ -109,6 +115,12 @@ func length(v interface{}, param string) error {
109115
func min(v interface{}, param string) error {
110116
st := reflect.ValueOf(v)
111117
invalid := false
118+
if st.Kind() == reflect.Ptr {
119+
if st.IsNil() {
120+
return nil
121+
}
122+
st = st.Elem()
123+
}
112124
switch st.Kind() {
113125
case reflect.String:
114126
p, err := asInt(param)
@@ -156,6 +168,12 @@ func min(v interface{}, param string) error {
156168
func max(v interface{}, param string) error {
157169
st := reflect.ValueOf(v)
158170
var invalid bool
171+
if st.Kind() == reflect.Ptr {
172+
if st.IsNil() {
173+
return nil
174+
}
175+
st = st.Elem()
176+
}
159177
switch st.Kind() {
160178
case reflect.String:
161179
p, err := asInt(param)
@@ -201,7 +219,14 @@ func max(v interface{}, param string) error {
201219
func regex(v interface{}, param string) error {
202220
s, ok := v.(string)
203221
if !ok {
204-
return ErrUnsupported
222+
sptr, ok := v.(*string)
223+
if !ok {
224+
return ErrUnsupported
225+
}
226+
if sptr == nil {
227+
return nil
228+
}
229+
s = *sptr
205230
}
206231

207232
re, err := regexp.Compile(param)

validator_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,20 @@ func (ms *MySuite) TestValidatePointerVar(c *C) {
313313

314314
err = validator.Validate(&test6{&test2{}})
315315
c.Assert(err, IsNil)
316+
317+
type test7 struct {
318+
A *string `validate:"min=6"`
319+
B *int `validate:"len=7"`
320+
C *int `validate:"min=12"`
321+
}
322+
s := "aaa"
323+
b := 8
324+
err = validator.Validate(&test7{&s, &b, nil})
325+
errs, ok = err.(validator.ErrorMap)
326+
c.Assert(ok, Equals, true)
327+
c.Assert(errs["A"], HasError, validator.ErrMin)
328+
c.Assert(errs["B"], HasError, validator.ErrLen)
329+
c.Assert(errs["C"], Not(HasError), validator.ErrMin)
316330
}
317331

318332
func (ms *MySuite) TestValidateOmittedStructVar(c *C) {

0 commit comments

Comments
 (0)