Skip to content

Commit

Permalink
add len,min,max,regex... support for pointer type
Browse files Browse the repository at this point in the history
  • Loading branch information
YueHonghui committed Sep 22, 2016
1 parent 0a9835d commit 027affc
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
27 changes: 26 additions & 1 deletion builtins.go
Expand Up @@ -62,6 +62,12 @@ func nonzero(v interface{}, param string) error {
func length(v interface{}, param string) error {
st := reflect.ValueOf(v)
valid := true
if st.Kind() == reflect.Ptr {
if st.IsNil() {
return nil
}
st = st.Elem()
}
switch st.Kind() {
case reflect.String:
p, err := asInt(param)
Expand Down Expand Up @@ -109,6 +115,12 @@ func length(v interface{}, param string) error {
func min(v interface{}, param string) error {
st := reflect.ValueOf(v)
invalid := false
if st.Kind() == reflect.Ptr {
if st.IsNil() {
return nil
}
st = st.Elem()
}
switch st.Kind() {
case reflect.String:
p, err := asInt(param)
Expand Down Expand Up @@ -156,6 +168,12 @@ func min(v interface{}, param string) error {
func max(v interface{}, param string) error {
st := reflect.ValueOf(v)
var invalid bool
if st.Kind() == reflect.Ptr {
if st.IsNil() {
return nil
}
st = st.Elem()
}
switch st.Kind() {
case reflect.String:
p, err := asInt(param)
Expand Down Expand Up @@ -201,7 +219,14 @@ func max(v interface{}, param string) error {
func regex(v interface{}, param string) error {
s, ok := v.(string)
if !ok {
return ErrUnsupported
sptr, ok := v.(*string)
if !ok {
return ErrUnsupported
}
if sptr == nil {
return nil
}
s = *sptr
}

re, err := regexp.Compile(param)
Expand Down
14 changes: 14 additions & 0 deletions validator_test.go
Expand Up @@ -313,6 +313,20 @@ func (ms *MySuite) TestValidatePointerVar(c *C) {

err = validator.Validate(&test6{&test2{}})
c.Assert(err, IsNil)

type test7 struct {
A *string `validate:"min=6"`
B *int `validate:"len=7"`
C *int `validate:"min=12"`
}
s := "aaa"
b := 8
err = validator.Validate(&test7{&s, &b, nil})
errs, ok = err.(validator.ErrorMap)
c.Assert(ok, Equals, true)
c.Assert(errs["A"], HasError, validator.ErrMin)
c.Assert(errs["B"], HasError, validator.ErrLen)
c.Assert(errs["C"], Not(HasError), validator.ErrMin)
}

func (ms *MySuite) TestValidateOmittedStructVar(c *C) {
Expand Down

0 comments on commit 027affc

Please sign in to comment.