mirror of
https://github.com/ent/ent.git
synced 2026-05-24 09:31:56 +03:00
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:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user