github.com/gogf/gf@v1.16.9/util/gvalid/gvalid_z_unit_i18n_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gvalid_test 8 9 import ( 10 "context" 11 "github.com/gogf/gf/debug/gdebug" 12 "github.com/gogf/gf/i18n/gi18n" 13 "github.com/gogf/gf/util/gvalid" 14 "testing" 15 16 "github.com/gogf/gf/test/gtest" 17 ) 18 19 func TestValidator_I18n(t *testing.T) { 20 var ( 21 err gvalid.Error 22 i18nManager = gi18n.New(gi18n.Options{Path: gdebug.TestDataPath("i18n")}) 23 ctxCn = gi18n.WithLanguage(context.TODO(), "cn") 24 validator = gvalid.New().I18n(i18nManager) 25 ) 26 gtest.C(t, func(t *gtest.T) { 27 err = validator.Rules("required").CheckValue("") 28 t.Assert(err.String(), "The field is required") 29 30 err = validator.Ctx(ctxCn).Rules("required").CheckValue("") 31 t.Assert(err.String(), "字段不能为空") 32 }) 33 gtest.C(t, func(t *gtest.T) { 34 err = validator.Ctx(ctxCn).Rules("required").Messages("CustomMessage").CheckValue("") 35 t.Assert(err.String(), "自定义错误") 36 }) 37 gtest.C(t, func(t *gtest.T) { 38 type Params struct { 39 Page int `v:"required|min:1 # page is required"` 40 Size int `v:"required|between:1,100 # size is required"` 41 ProjectId int `v:"between:1,10000 # project id must between :min, :max"` 42 } 43 obj := &Params{ 44 Page: 1, 45 Size: 10, 46 } 47 err := validator.Ctx(ctxCn).CheckStruct(obj) 48 t.Assert(err.String(), "项目ID必须大于等于1并且要小于等于10000") 49 }) 50 }