2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2020-07-05 18:55:38 +08:00
|
|
|
//
|
|
|
|
// 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-05-19 22:33:50 +08:00
|
|
|
import "context"
|
|
|
|
|
2020-07-05 18:55:38 +08:00
|
|
|
// RuleFunc is the custom function for data validation.
|
2021-03-23 17:53:20 +08:00
|
|
|
// The parameter `rule` specifies the validation rule string, like "required", "between:1,100", etc.
|
|
|
|
// The parameter `value` specifies the value for this rule to validate.
|
|
|
|
// The parameter `message` specifies the custom error message or configured i18n message for this rule.
|
2021-05-29 11:30:34 +08:00
|
|
|
// The parameter `data` specifies the `data` which is passed to the Validator. It might be 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.
|
|
|
|
type RuleFunc func(ctx context.Context, rule string, value interface{}, message string, data interface{}) error
|
2020-07-05 18:55:38 +08:00
|
|
|
|
|
|
|
var (
|
|
|
|
// customRuleFuncMap stores the custom rule functions.
|
2020-10-21 00:08:36 +08:00
|
|
|
// map[Rule]RuleFunc
|
2020-07-05 18:55:38 +08:00
|
|
|
customRuleFuncMap = make(map[string]RuleFunc)
|
|
|
|
)
|
|
|
|
|
|
|
|
// RegisterRule registers custom validation rule and function for package.
|
|
|
|
// It returns error if there's already the same rule registered previously.
|
|
|
|
func RegisterRule(rule string, f RuleFunc) error {
|
|
|
|
customRuleFuncMap[rule] = f
|
|
|
|
return nil
|
|
|
|
}
|
2020-09-22 08:45:22 +08:00
|
|
|
|
|
|
|
// DeleteRule deletes custom defined validation rule and its function from global package.
|
|
|
|
func DeleteRule(rule string) {
|
|
|
|
delete(customRuleFuncMap, rule)
|
|
|
|
}
|