Skip to content

Commit

Permalink
feat(validation): adds support for patternDescription tag for human-r…
Browse files Browse the repository at this point in the history
…eadable validation messages when using patterns
  • Loading branch information
purin-dev committed Mar 18, 2024
1 parent 428dcfd commit c714e04
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
8 changes: 7 additions & 1 deletion schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand Down
8 changes: 8 additions & 0 deletions validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit c714e04

Please sign in to comment.