github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin.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 builtin implements built-in validation rules.
     8  //
     9  // Referred to Laravel validation:
    10  // https://laravel.com/docs/master/validation#available-validation-rules
    11  package builtin
    12  
    13  import (
    14  	"reflect"
    15  
    16  	"github.com/gogf/gf/v2/container/gvar"
    17  )
    18  
    19  type Rule interface {
    20  	// Name returns the builtin name of the rule.
    21  	Name() string
    22  
    23  	// Message returns the default error message of the rule.
    24  	Message() string
    25  
    26  	// Run starts running the rule, it returns nil if successful, or else an error.
    27  	Run(in RunInput) error
    28  }
    29  
    30  type RunInput struct {
    31  	RuleKey     string       // RuleKey is like the "max" in rule "max: 6"
    32  	RulePattern string       // RulePattern is like "6" in rule:"max:6"
    33  	Field       string       // The field name of Value.
    34  	ValueType   reflect.Type // ValueType specifies the type of the value, which might be nil.
    35  	Value       *gvar.Var    // Value specifies the value for this rule to validate.
    36  	Data        *gvar.Var    // Data specifies the `data` which is passed to the Validator.
    37  	Message     string       // Message specifies the custom error message or configured i18n message for this rule.
    38  	Option      RunOption    // Option provides extra configuration for validation rule.
    39  }
    40  
    41  type RunOption struct {
    42  	CaseInsensitive bool // CaseInsensitive indicates that it does Case-Insensitive comparison in string.
    43  }
    44  
    45  var (
    46  	// ruleMap stores all builtin validation rules.
    47  	ruleMap = map[string]Rule{}
    48  )
    49  
    50  // Register registers builtin rule into manager.
    51  func Register(rule Rule) {
    52  	ruleMap[rule.Name()] = rule
    53  }
    54  
    55  // GetRule retrieves and returns rule by `name`.
    56  func GetRule(name string) Rule {
    57  	return ruleMap[name]
    58  }