github.com/wangyougui/gf/v2@v2.6.5/util/gvalid/internal/builtin/builtin_lte.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/wangyougui/gf.
     6  
     7  package builtin
     8  
     9  import (
    10  	"errors"
    11  	"strconv"
    12  
    13  	"github.com/wangyougui/gf/v2/text/gstr"
    14  	"github.com/wangyougui/gf/v2/util/gconv"
    15  	"github.com/wangyougui/gf/v2/util/gutil"
    16  )
    17  
    18  // RuleLTE implements `lte` rule:
    19  // Lesser than or equal to `field`.
    20  // It supports both integer and float.
    21  //
    22  // Format: lte:field
    23  type RuleLTE struct{}
    24  
    25  func init() {
    26  	Register(RuleLTE{})
    27  }
    28  
    29  func (r RuleLTE) Name() string {
    30  	return "lte"
    31  }
    32  
    33  func (r RuleLTE) Message() string {
    34  	return "The {field} value `{value}` must be lesser than or equal to field {field1} value `{value1}`"
    35  }
    36  
    37  func (r RuleLTE) Run(in RunInput) error {
    38  	var (
    39  		fieldName, fieldValue = gutil.MapPossibleItemByKey(in.Data.Map(), in.RulePattern)
    40  		fieldValueN, err1     = strconv.ParseFloat(gconv.String(fieldValue), 10)
    41  		valueN, err2          = strconv.ParseFloat(in.Value.String(), 10)
    42  	)
    43  
    44  	if valueN > fieldValueN || err1 != nil || err2 != nil {
    45  		return errors.New(gstr.ReplaceByMap(in.Message, map[string]string{
    46  			"{field1}": fieldName,
    47  			"{value1}": gconv.String(fieldValue),
    48  		}))
    49  	}
    50  	return nil
    51  }