Files
gf/util/gvalid/gvalid_custom_rule.go

58 lines
1.7 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gvalid
2021-11-09 14:31:16 +08:00
import (
"context"
2021-11-13 23:30:31 +08:00
2021-11-09 14:31:16 +08:00
"github.com/gogf/gf/v2/container/gvar"
)
// RuleFunc is the custom function for data validation.
2021-11-09 14:31:16 +08:00
type RuleFunc func(ctx context.Context, in RuleFuncInput) error
// RuleFuncInput holds the input parameters that passed to custom rule function RuleFunc.
type RuleFuncInput struct {
// Rule specifies the validation rule string, like "required", "between:1,100", etc.
Rule string
// Message specifies the custom error message or configured i18n message for this rule.
Message string
// Value specifies the value for this rule to validate.
Value *gvar.Var
// Data specifies the `data` which is passed to the Validator. It might be a type of map/struct or a nil value.
// You can ignore the parameter `Data` if you do not really need it in your custom validation rule.
Data *gvar.Var
}
var (
// customRuleFuncMap stores the custom rule functions.
// map[Rule]RuleFunc
customRuleFuncMap = make(map[string]RuleFunc)
)
// RegisterRule registers custom validation rule and function for package.
2021-11-09 15:22:17 +08:00
func RegisterRule(rule string, f RuleFunc) {
customRuleFuncMap[rule] = f
}
2021-11-09 14:31:16 +08:00
// RegisterRuleByMap registers custom validation rules using map for package.
2021-11-09 15:22:17 +08:00
func RegisterRuleByMap(m map[string]RuleFunc) {
2021-11-09 14:31:16 +08:00
for k, v := range m {
customRuleFuncMap[k] = v
}
}
// DeleteRule deletes custom defined validation one or more rules and associated functions from global package.
func DeleteRule(rules ...string) {
for _, rule := range rules {
delete(customRuleFuncMap, rule)
}
}