Skip to content

Commit

Permalink
fix some bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Dec 22, 2018
1 parent c45f314 commit 04fecb2
Show file tree
Hide file tree
Showing 10 changed files with 248 additions and 133 deletions.
10 changes: 4 additions & 6 deletions data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ func (d *MapData) Validation(err ...error) *Validation {
if len(err) > 0 {
return NewValidation(d).WithError(err[0])
}

return NewValidation(d)
}

Expand All @@ -94,7 +93,6 @@ func (d *MapData) BindJSON(ptr interface{}) error {
if len(d.bodyJSON) == 0 {
return nil
}

return Unmarshal(d.bodyJSON, ptr)
}

Expand Down Expand Up @@ -350,7 +348,6 @@ func (d *FormData) Validation(err ...error) *Validation {
if len(err) > 0 && err[0] != nil {
return NewValidation(d).WithError(err[0])
}

return NewValidation(d)
}

Expand Down Expand Up @@ -401,15 +398,16 @@ func (d *FormData) Encode() string {
}

// Set sets the key to value. It replaces any existing values.
func (d *FormData) Set(field string, val interface{}) error {
func (d *FormData) Set(field string, val interface{}) (err error) {
switch val.(type) {
case string:
d.Form.Set(field, val.(string))
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
d.Form.Set(field, fmt.Sprint(val))
default:
err = ErrSetValue
}

return ErrSetValue
return
}

// Get value by key
Expand Down
File renamed without changes.
6 changes: 4 additions & 2 deletions generic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,11 @@ func TestFormData(t *testing.T) {
is.Equal("inhere", d.String("name"))
is.Equal("age=30&money=23.4&name=inhere&notify=true", d.Encode())

d.Set("newKey", "strVal")
err := d.Set("newKey", "strVal")
is.NoError(err)
is.Equal("strVal", d.String("newKey"))
d.Set("newInt", 23)
err = d.Set("newInt", 23)
is.NoError(err)
is.Equal(23, d.Int("newInt"))
is.Error(d.Set("invalid", []int{2}))

Expand Down
7 changes: 0 additions & 7 deletions helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ func stringSplit(str, sep string) (ss []string) {
ss = append(ss, val)
}
}

return
}

Expand All @@ -45,7 +44,6 @@ func strings2Args(strings []string) []interface{} {
for i, s := range strings {
args[i] = s
}

return args
}

Expand Down Expand Up @@ -128,7 +126,6 @@ func CalcLength(val interface{}) int {
if str, ok := val.(string); ok {
return len(str)
}

return ValueLen(reflect.ValueOf(val))
}

Expand Down Expand Up @@ -168,7 +165,6 @@ func valueCompare(srcVal, dstVal interface{}, op string) (ok bool) {
case "gte":
ok = srcInt >= dstInt
}

return
}

Expand Down Expand Up @@ -224,7 +220,6 @@ func getSliceItemKind(typString string) reflect.Kind {
case "[]string":
return reflect.String
}

return reflect.Invalid
}

Expand All @@ -246,7 +241,6 @@ func convertType(srcVal interface{}, srcKind kind, dstType reflect.Kind) (interf
return fmt.Sprint(i64), nil
}
}

return nil, nil
}

Expand Down Expand Up @@ -343,7 +337,6 @@ func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
return v, true
}
}

return v, false
}

Expand Down
1 change: 0 additions & 1 deletion quick_start.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ func FromMap(m map[string]interface{}) *MapData {
data.Map = m
data.value = reflect.ValueOf(m)
}

return data
}

Expand Down
7 changes: 2 additions & 5 deletions validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,6 @@ func (r *Rule) Apply(v *Validation) (stop bool) {
return true
}
}

continue
}

Expand Down Expand Up @@ -235,7 +234,6 @@ func (r *Rule) fileValidate(field, name string, v *Validation) (ok bool) {
ok = v.InMimeTypes(fd, field, ss[0], ss[1:]...)
}
}

return
}

Expand Down Expand Up @@ -394,8 +392,8 @@ func callValidator(v *Validation, fm *funcMeta, field string, val interface{}, a
return
}

// fmt.Println(fm.name, val)
// fmt.Printf("%#v\n", args)
// fmt.Println(fm.name)
// fmt.Printf("%T %+v | %#v\n", val, val, args)

// 2. call built in validator
switch fm.name {
Expand Down Expand Up @@ -447,7 +445,6 @@ func callValidator(v *Validation, fm *funcMeta, field string, val interface{}, a
// 3. call user custom validators
ok = callValidatorValue(fm.fv, val, args)
}

return
}

Expand Down
33 changes: 19 additions & 14 deletions validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,12 @@ type Validation struct {
filterValues map[string]reflect.Value
}

// NewValidation instance
// NewEmpty new validation instance, but not add data.
func NewEmpty(scene ...string) *Validation {
return NewValidation(nil, scene...)
}

// NewValidation new validation instance
func NewValidation(data DataFace, scene ...string) *Validation {
v := &Validation{
Errors: make(Errors),
Expand Down Expand Up @@ -151,7 +156,6 @@ func newWithError(d DataFace, err error) *Validation {
if err != nil {
return NewValidation(d).WithError(err)
}

return NewValidation(d)
}

Expand All @@ -163,9 +167,9 @@ func newWithError(d DataFace, err error) *Validation {
*************************************************************/

// Config the Validation instance
func (v *Validation) Config(fn func(v *Validation)) {
fn(v)
}
// func (v *Validation) Config(fn func(v *Validation)) {
// fn(v)
// }

// ResetResult reset the validate result.
func (v *Validation) ResetResult() {
Expand All @@ -185,14 +189,15 @@ func (v *Validation) Reset() {
// rules
v.rules = v.rules[:0]
v.filterRules = v.filterRules[:0]
v.validators = make(map[string]int)
}

// WithScenarios is alias of the WithScenes()
func (v *Validation) WithScenarios(scenes SValues) *Validation {
return v.WithScenes(scenes)
}

// WithScenes config.
// WithScenes set scene config.
// Usage:
// v.WithScenes(SValues{
// "create": []string{"name", "email"},
Expand Down Expand Up @@ -220,7 +225,6 @@ func (v *Validation) SetScene(scene ...string) *Validation {
if len(scene) > 0 {
v.AtScene(scene[0])
}

return v
}

Expand Down Expand Up @@ -276,7 +280,6 @@ func (v *Validation) StringRules(mp MS) *Validation {
for name, rule := range mp {
v.StringRule(name, rule)
}

return v
}

Expand Down Expand Up @@ -337,7 +340,6 @@ func (v *Validation) validatorMeta(name string) *funcMeta {
return fm
}
}

return nil
}

Expand Down Expand Up @@ -366,7 +368,6 @@ func (v *Validation) Validators(withGlobal bool) map[string]int {
for name, typ := range v.validators {
mp[name] = typ
}

return mp
}

Expand Down Expand Up @@ -395,20 +396,25 @@ func (v *Validation) Validate(scene ...string) bool {

// apply rule to validate data.
for _, rule := range v.rules {
// has error and v.StopOnError is true.
if rule.Apply(v) {
break
}
}

v.hasValidated = true
if v.hasError { // clear safe data.
if v.hasError {
// clear safe data will error.
v.safeData = make(map[string]interface{})
}

return v.IsSuccess()
}

// ValidateData validate given data
func (v *Validation) ValidateData(data DataFace) bool {
v.data = data
return v.Validate()
}

/*************************************************************
* Do filtering/sanitize
*************************************************************/
Expand Down Expand Up @@ -594,7 +600,6 @@ func (v *Validation) sceneFieldMap() (m map[string]uint8) {
m[field] = 1
}
}

return
}

Expand Down
44 changes: 39 additions & 5 deletions validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ func TestMap(t *testing.T) {
is.Contains(v.Errors.String(), "cannot convert invalid to int64")

v = New(mpSample)
v.StringRule("newSt", "") // will ignore
v.StringRule("newSt", "gtField:oldSt")
v.StringRule("newSt", "gteField:oldSt")
v.StringRule("newSt", "neField:oldSt")
Expand Down Expand Up @@ -346,11 +347,11 @@ func TestRequest(t *testing.T) {
mw := multipart.NewWriter(buf)
w, err := mw.CreateFormFile("file", "test.jpg")
if is.NoError(err) {
w.Write([]byte("\xFF\xD8\xFF")) // write file content
_, _ = w.Write([]byte("\xFF\xD8\xFF")) // write file content
}
mw.WriteField("age", "24")
mw.WriteField("name", "inhere")
mw.Close()
_ = mw.WriteField("age", "24")
_ = mw.WriteField("name", "inhere")
_ = mw.Close()

r, _ = http.NewRequest("POST", "/users", buf)
r.Header.Set("Content-Type", mw.FormDataContentType())
Expand Down Expand Up @@ -408,7 +409,8 @@ func TestRequest(t *testing.T) {
v.StringRule("name", "-", "trim|upper")
v.Validate() // validate
is.True(v.IsOK())
v.BindSafeData(user)
err = v.BindSafeData(user)
is.NoError(err)
is.Equal("INHERE", user.Name)

// error content type
Expand Down Expand Up @@ -538,3 +540,35 @@ func TestAddValidator(t *testing.T) {
is.NotContains(v.Validators(false), "min")
is.Contains(v.Validators(true), "min")
}

func TestValidation_ValidateData(t *testing.T) {
d := FromMap(M{
"name": "inhere",
"json": `{"k": "v"}`,
})

v := NewEmpty()
v.StringRules(MS{
"json": "json",
})

ok := v.ValidateData(d)
assert.True(t, ok)

v.Reset()
assert.Len(t, v.Validators(false), 0)
}

func TestIssue2(t *testing.T) {
type Fl struct {
A float64 `validate:"float"`
}

fl := Fl{123}
v := Struct(fl)
assert.True(t, v.Validate())
}

func TestBuiltInValidators(t *testing.T) {

}
Loading

0 comments on commit 04fecb2

Please sign in to comment.