github.com/gogf/gf/v2@v2.7.4/util/gvalid/internal/builtin/builtin_gt.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  	"strconv"
    12  
    13  	"github.com/gogf/gf/v2/text/gstr"
    14  	"github.com/gogf/gf/v2/util/gconv"
    15  	"github.com/gogf/gf/v2/util/gutil"
    16  )
    17  
    18  // RuleGT implements `gt` rule:
    19  // Greater than `field`.
    20  // It supports both integer and float.
    21  //
    22  // Format: gt:field
    23  type RuleGT struct{}
    24  
    25  func init() {
    26  	Register(RuleGT{})
    27  }
    28  
    29  func (r RuleGT) Name() string {
    30  	return "gt"
    31  }
    32  
    33  func (r RuleGT) Message() string {
    34  	return "The {field} value `{value}` must be greater than field {field1} value `{value1}`"
    35  }
    36  
    37  func (r RuleGT) 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  }