Skip to content

Commit

Permalink
Merge pull request #323 from purin-dev/custom-validation-message
Browse files Browse the repository at this point in the history
 feat(validation): flexible validation messages for pattern tag
  • Loading branch information
danielgtaylor authored Mar 18, 2024
2 parents 428dcfd + 6a61a25 commit c312351
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
9 changes: 8 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 @@ -141,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},
Expand Down Expand Up @@ -187,7 +189,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 +504,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 c312351

Please sign in to comment.