-
Notifications
You must be signed in to change notification settings - Fork 969
schema/field: validate rune length with MinRuneLen
/ MaxRuneLen
#4398
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Hey! Thanks for the contribution, but we can’t accept this change, as it will introduce a breaking-change. Please follow this custom validator example in our doc: https://entgo.io/docs/schema-fields#validators // MaxRuneCount validates the rune length of a string by using the unicode/utf8 package.
func MaxRuneCount(maxLen int) func(s string) error {
return func(s string) error {
if utf8.RuneCountInString(s) > maxLen {
return errors.New("value is more than the max length")
}
return nil
}
}
field.String("name").
// If using a SQL-database: change the underlying data type to varchar(10).
Annotations(entsql.Annotation{
Size: 10,
}).
Validate(MaxRuneCount(10))
field.String("nickname").
// If using a SQL-database: change the underlying data type to varchar(20).
Annotations(entsql.Annotation{
Size: 20,
}).
Validate(MaxRuneCount(20)) |
Thanks for the reply! Adding a new method with no disruptive changes. |
Thanks for the contribution, but I don't see a reason to add it to the standard ent validators. @giautm, @masseelch - your thoughts? |
I think it's okay to have this in standard functions, it make life more easy. |
I agree with Giau |
LGTM then. @liangminhua, just add a small unit-test for it, and one of us will merge this. |
1cc0d1c
to
666c22f
Compare
Signed-off-by: liangminhua <ben302010@live.cn>
Thanks for the review! ✅ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
cc @giautm
MinRuneLen
/ MaxRuneLen
MaxLen
validator usedlen(v)
(byte count), while databases like MySQL/PostgreSQL/SQLite definevarchar(size)
as character count (not bytes). This caused inconsistent validation for multi-byte characters (e.g., Chinese, Emoji).utf8.RuneCountInString(v)
to count Unicode characters, ensuring the validation aligns with database constraints.varchar
uses byte counts by default), explicit syntax likevarchar(N CHAR)
ornvarchar
can enforce character limits. This change does not affect existing logic but should be noted for future dialect support.