github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_required.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 8 9 import ( 10 "errors" 11 "reflect" 12 13 "github.com/gogf/gf/v2/util/gconv" 14 ) 15 16 // RuleRequired implements `required` rule. 17 // Format: required 18 type RuleRequired struct{} 19 20 func init() { 21 Register(RuleRequired{}) 22 } 23 24 func (r RuleRequired) Name() string { 25 return "required" 26 } 27 28 func (r RuleRequired) Message() string { 29 return "The {field} field is required" 30 } 31 32 func (r RuleRequired) Run(in RunInput) error { 33 if isRequiredEmpty(in.Value.Val()) { 34 return errors.New(in.Message) 35 } 36 return nil 37 } 38 39 // isRequiredEmpty checks and returns whether given value is empty string. 40 // Note that if given value is a zero integer, it will be considered as not empty. 41 func isRequiredEmpty(value interface{}) bool { 42 reflectValue := reflect.ValueOf(value) 43 for reflectValue.Kind() == reflect.Ptr { 44 reflectValue = reflectValue.Elem() 45 } 46 switch reflectValue.Kind() { 47 case reflect.String, reflect.Map, reflect.Array, reflect.Slice: 48 return reflectValue.Len() == 0 49 } 50 return gconv.String(value) == "" 51 }