From c714e04d4a1130313df5d7ed47e8180ed4903f6d Mon Sep 17 00:00:00 2001 From: Blair Date: Sun, 17 Mar 2024 21:06:49 -0400 Subject: [PATCH 1/2] feat(validation): adds support for patternDescription tag for human-readable validation messages when using patterns --- schema.go | 8 +++++++- validate_test.go | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/schema.go b/schema.go index 4bebcd5f..f177db21 100644 --- a/schema.go +++ b/schema.go @@ -77,6 +77,7 @@ type Schema struct { MinLength *int `yaml:"minLength,omitempty"` MaxLength *int `yaml:"maxLength,omitempty"` Pattern string `yaml:"pattern,omitempty"` + PatternDescription string `yaml:"patternDescription,omitempty"` MinItems *int `yaml:"minItems,omitempty"` MaxItems *int `yaml:"maxItems,omitempty"` UniqueItems bool `yaml:"uniqueItems,omitempty"` @@ -187,7 +188,11 @@ func (s *Schema) PrecomputeMessages() { } if s.Pattern != "" { s.patternRe = regexp.MustCompile(s.Pattern) - s.msgPattern = "expected string to match pattern " + s.Pattern + if s.PatternDescription != "" { + s.msgPattern = "expected string to be " + s.PatternDescription + } else { + s.msgPattern = "expected string to match pattern " + s.Pattern + } } if s.MinItems != nil { s.msgMinItems = fmt.Sprintf("expected array length >= %d", *s.MinItems) @@ -498,6 +503,7 @@ func SchemaFromField(registry Registry, f reflect.StructField, hint string) *Sch fs.MinLength = intTag(f, "minLength") fs.MaxLength = intTag(f, "maxLength") fs.Pattern = f.Tag.Get("pattern") + fs.PatternDescription = f.Tag.Get("patternDescription") fs.MinItems = intTag(f, "minItems") fs.MaxItems = intTag(f, "maxItems") fs.UniqueItems = boolTag(f, "uniqueItems") diff --git a/validate_test.go b/validate_test.go index 20201cc5..4a26261b 100644 --- a/validate_test.go +++ b/validate_test.go @@ -265,6 +265,14 @@ var validateTests = []struct { input: map[string]any{"value": "a1"}, errs: []string{"expected string to match pattern ^[a-z]+$"}, }, + { + name: "pattern custom message fail", + typ: reflect.TypeOf(struct { + Value string `json:"value" pattern:"^[a-z]+$" patternDescription:"alphabetical"` + }{}), + input: map[string]any{"value": "b@2"}, + errs: []string{"expected string to be alphabetical"}, + }, { name: "pattern invalid", typ: reflect.TypeOf(struct { From 6a61a2543debd0b474949c8188b0c86f2e4daea5 Mon Sep 17 00:00:00 2001 From: "Daniel G. Taylor" Date: Mon, 18 Mar 2024 08:29:45 -0700 Subject: [PATCH 2/2] fix: add patternDescription to custom marshaler --- schema.go | 1 + 1 file changed, 1 insertion(+) diff --git a/schema.go b/schema.go index f177db21..25f1539e 100644 --- a/schema.go +++ b/schema.go @@ -142,6 +142,7 @@ func (s *Schema) MarshalJSON() ([]byte, error) { {"minLength", s.MinLength, omitEmpty}, {"maxLength", s.MaxLength, omitEmpty}, {"pattern", s.Pattern, omitEmpty}, + {"patternDescription", s.PatternDescription, omitEmpty}, {"minItems", s.MinItems, omitEmpty}, {"maxItems", s.MaxItems, omitEmpty}, {"uniqueItems", s.UniqueItems, omitEmpty},