github.com/gogf/gf/v2@v2.7.4/util/gvalid/gvalid_validator_message.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 gvalid
     8  
     9  import (
    10  	"context"
    11  
    12  	"github.com/gogf/gf/v2/util/gvalid/internal/builtin"
    13  )
    14  
    15  // getErrorMessageByRule retrieves and returns the error message for specified rule.
    16  // It firstly retrieves the message from custom message map, and then checks i18n manager,
    17  // it returns the default error message if it's not found in neither custom message map nor i18n manager.
    18  func (v *Validator) getErrorMessageByRule(ctx context.Context, ruleKey string, customMsgMap map[string]string) string {
    19  	content := customMsgMap[ruleKey]
    20  	if content != "" {
    21  		// I18n translation.
    22  		i18nContent := v.i18nManager.GetContent(ctx, content)
    23  		if i18nContent != "" {
    24  			return i18nContent
    25  		}
    26  		return content
    27  	}
    28  
    29  	// Retrieve default message according to certain rule.
    30  	content = v.i18nManager.GetContent(ctx, ruleMessagePrefixForI18n+ruleKey)
    31  	if content == "" {
    32  		content = defaultErrorMessages[ruleKey]
    33  	}
    34  	// Builtin rule message.
    35  	if content == "" {
    36  		if builtinRule := builtin.GetRule(ruleKey); builtinRule != nil {
    37  			content = builtinRule.Message()
    38  		}
    39  	}
    40  	// If there's no configured rule message, it uses default one.
    41  	if content == "" {
    42  		content = v.i18nManager.GetContent(ctx, ruleMessagePrefixForI18n+internalDefaultRuleName)
    43  	}
    44  	// If there's no configured rule message, it uses default one.
    45  	if content == "" {
    46  		content = defaultErrorMessages[internalDefaultRuleName]
    47  	}
    48  	return content
    49  }