1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 19:10:54 +00:00

Merge pull request #2728 from miraclesu/validation

validation: support int64 int32 int16 and int8 type on 64-bit platform
This commit is contained in:
astaxie 2017-07-01 15:35:48 +08:00 committed by GitHub
commit cb86bcc9e8
2 changed files with 70 additions and 10 deletions

View File

@ -25,6 +25,8 @@ import (
const (
// ValidTag struct tag
ValidTag = "valid"
wordsize = 32 << (^uint(0) >> 32 & 1)
)
var (
@ -43,6 +45,8 @@ var (
"Valid": true,
"NoMatch": true,
}
Int64On32Err = fmt.Errorf("not support int64 on 32-bit platform")
)
func init() {
@ -249,16 +253,39 @@ func parseParam(t reflect.Type, s string) (i interface{}, err error) {
switch t.Kind() {
case reflect.Int:
i, err = strconv.Atoi(s)
case reflect.Int64:
if wordsize == 32 {
return nil, Int64On32Err
}
i, err = strconv.ParseInt(s, 10, 64)
case reflect.Int32:
var v int64
v, err = strconv.ParseInt(s, 10, 32)
if err == nil {
i = int32(v)
}
case reflect.Int16:
var v int64
v, err = strconv.ParseInt(s, 10, 16)
if err == nil {
i = int16(v)
}
case reflect.Int8:
var v int64
v, err = strconv.ParseInt(s, 10, 8)
if err == nil {
i = int8(v)
}
case reflect.String:
i = s
case reflect.Ptr:
if t.Elem().String() != "regexp.Regexp" {
err = fmt.Errorf("does not support %s", t.Elem().String())
err = fmt.Errorf("not support %s", t.Elem().String())
return
}
i, err = regexp.Compile(s)
default:
err = fmt.Errorf("does not support %s", t.Kind().String())
err = fmt.Errorf("not support %s", t.Kind().String())
}
return
}

View File

@ -166,13 +166,29 @@ type Min struct {
}
// IsSatisfied judge whether obj is valid
// not support int64 on 32-bit platform
func (m Min) IsSatisfied(obj interface{}) bool {
num, ok := obj.(int)
if ok {
return num >= m.Min
}
var v int
switch obj.(type) {
case int64:
if wordsize == 32 {
return false
}
v = int(obj.(int64))
case int:
v = obj.(int)
case int32:
v = int(obj.(int32))
case int16:
v = int(obj.(int16))
case int8:
v = int(obj.(int8))
default:
return false
}
return v >= m.Min
}
// DefaultMessage return the default min error message
func (m Min) DefaultMessage() string {
@ -196,13 +212,29 @@ type Max struct {
}
// IsSatisfied judge whether obj is valid
// not support int64 on 32-bit platform
func (m Max) IsSatisfied(obj interface{}) bool {
num, ok := obj.(int)
if ok {
return num <= m.Max
}
var v int
switch obj.(type) {
case int64:
if wordsize == 32 {
return false
}
v = int(obj.(int64))
case int:
v = obj.(int)
case int32:
v = int(obj.(int32))
case int16:
v = int(obj.(int16))
case int8:
v = int(obj.(int8))
default:
return false
}
return v <= m.Max
}
// DefaultMessage return the default max error message
func (m Max) DefaultMessage() string {
@ -227,6 +259,7 @@ type Range struct {
}
// IsSatisfied judge whether obj is valid
// not support int64 on 32-bit platform
func (r Range) IsSatisfied(obj interface{}) bool {
return r.Min.IsSatisfied(obj) && r.Max.IsSatisfied(obj)
}