Skip to content

Commit 3e4f090

Browse files
committed
Validation: use lang.Default if no lang option provided
1 parent b3ecb6d commit 3e4f090

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

lang/default.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,11 @@ var enUS = &Language{
207207
},
208208
}
209209

210+
// Default language used if no language is provided in a feature's options.
211+
// By default, equals to the built-in "en-US" language.
212+
// Although it can be replaced, writing to this variable is not concurrently safe.
213+
var Default = enUS
214+
210215
// SetDefaultLine set the language line identified by the given key in the
211216
// default "en-US" language.
212217
// Values set this way can be overridden by language files.

validation/validator.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,10 @@ type Options struct {
114114
// To avoid allocating when assigning to an `interface{}`, context keys often have
115115
// concrete type `struct{}`. Alternatively, exported context key variables' static
116116
// type should be a pointer or interface.
117-
Extra map[any]any
117+
Extra map[any]any
118+
119+
// Language used for translating validation error messages.
120+
// Defaults to `lang.Default`.
118121
Language *lang.Language
119122
DB *gorm.DB
120123
Config *config.Config
@@ -275,6 +278,9 @@ func Validate(options *Options) (*Errors, []error) {
275278
if options.Extra == nil {
276279
options.Extra = map[any]any{}
277280
}
281+
if options.Language == nil {
282+
options.Language = lang.Default
283+
}
278284

279285
rules := options.Rules.AsRules()
280286
for _, field := range rules {

validation/validator_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -890,6 +890,23 @@ func TestValidate(t *testing.T) {
890890
},
891891
},
892892
},
893+
{
894+
desc: "no_language_provided_in_options",
895+
options: &Options{
896+
Data: map[string]any{"property": nil},
897+
Rules: RuleSet{
898+
{Path: "property", Rules: List{Required()}},
899+
},
900+
},
901+
wantValidationErrors: &Errors{
902+
Fields: FieldsErrors{
903+
"property": &Errors{
904+
Errors: []string{"The property is required."}, // Translated message (using lang.Default)
905+
},
906+
},
907+
},
908+
wantData: map[string]any{},
909+
},
893910
}
894911

895912
for _, c := range cases {

0 commit comments

Comments
 (0)