schema/field: add MaxLen built-in validator to bytes fields (#1863)

* added MaxLen built-in validator to `[]byte`

* typo

* move test to type_test.go

* Update doc/md/schema-fields.md

Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com>

Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com>
This commit is contained in:
Amit Shani
2021-08-24 10:23:43 +03:00
committed by GitHub
parent d84ac191b1
commit ad792fe79e
29 changed files with 649 additions and 13 deletions

View File

@@ -579,6 +579,12 @@ func (b *bytesBuilder) StructTag(s string) *bytesBuilder {
// In SQLite, it does not have any effect on the type size, which is default to 1B bytes.
func (b *bytesBuilder) MaxLen(i int) *bytesBuilder {
b.desc.Size = i
b.desc.Validators = append(b.desc.Validators, func(buf []byte) error {
if len(buf) > i {
return errors.New("value is greater than the required length")
}
return nil
})
return b
}

View File

@@ -199,6 +199,7 @@ func TestBytes(t *testing.T) {
Validate(func(bytes []byte) error {
return nil
}).
MaxLen(50).
Descriptor()
assert.Equal(t, "active", fd.Name)
assert.True(t, fd.Unique)
@@ -206,7 +207,7 @@ func TestBytes(t *testing.T) {
assert.NotNil(t, fd.Default)
assert.Equal(t, []byte("{}"), fd.Default)
assert.Equal(t, "comment", fd.Comment)
assert.Len(t, fd.Validators, 1)
assert.Len(t, fd.Validators, 2)
fd = field.Bytes("ip").GoType(net.IP("127.0.0.1")).Descriptor()
assert.NoError(t, fd.Err)