Skip to content

Commit

Permalink
fix(ir): add support for byte format in string validation
Browse files Browse the repository at this point in the history
  • Loading branch information
k4n4ry committed Aug 12, 2024
1 parent 3d71775 commit c1c523a
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions gen/_template/validators.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
MaxLength: {{ $v.MaxLength }},
MaxLengthSet: {{ $v.MaxLengthSet }},
Email: {{ $v.Email }},
Byte: {{ $v.Byte }},
Hostname: {{ $v.Hostname }},
{{- if $v.Regex }}
Regex: regexMap[{{ quote $v.Regex }}],
Expand Down
3 changes: 3 additions & 0 deletions gen/ir/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ func (v *Validators) SetString(schema *jsonschema.Schema) (err error) {
if schema.Format == "hostname" {
v.String.Hostname = true
}
if schema.Format == "byte" {
v.String.Byte = true
}
return nil
}

Expand Down
7 changes: 6 additions & 1 deletion validate/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type String struct {
MaxLength int
MaxLengthSet bool
Email bool
Byte bool
Regex ogenregex.Regexp
Hostname bool
}
Expand Down Expand Up @@ -100,12 +101,16 @@ func (t String) checkEmail(v string) error {

// Validate returns error if v does not match validation rules.
func (t String) Validate(v string) error {
length := len([]rune(v))
if t.Byte {
length = len([]byte(v))
}
if err := (Array{
MinLength: t.MinLength,
MinLengthSet: t.MinLengthSet,
MaxLength: t.MaxLength,
MaxLengthSet: t.MaxLengthSet,
}).ValidateLength(len([]rune(v))); err != nil {
}).ValidateLength(length); err != nil {
return err
}
if t.Email {
Expand Down
23 changes: 23 additions & 0 deletions validate/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,29 @@ func TestHostname(t *testing.T) {
}
}

func TestByte(t *testing.T) {
v := String{Byte: true}
v.SetMinLength(2)
v.SetMaxLength(5)
require.True(t, v.Set())

for _, b := range [][]byte{
[]byte("12"),
[]byte("abcde"),
[]byte("α"), // equals []byte{0xCE, 0xB1}
} {
require.NoError(t, v.Validate(string(b)))
}
for _, b := range [][]byte{
[]byte("1"),
[]byte("abcdef"),
[]byte(""),
[]byte("αβγ"), // equals []byte{0xCE, 0xB1, 0xCE, 0xB2, 0xCE, 0xB3}
} {
require.Error(t, v.Validate(string(b)), "%q should be invalid", b)
}
}

func TestRegex(t *testing.T) {
v := String{Regex: ogenregex.MustCompile(`^\d$`)}
require.True(t, v.Set())
Expand Down

0 comments on commit c1c523a

Please sign in to comment.