Skip to content
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

fix: length validation for utf8 strings #298

Merged
merged 1 commit into from
Mar 13, 2024

Conversation

maximdanilchenko
Copy link
Contributor

Hi! Current string length validation made with go's standard len function works incorrectly with non ascii characters. So if there any non-english symbols "maxLength" validator will fail when it shouldn't.

In this PR I'v replaced len with utf8.RuneCountInString. Instead of number of bytes it will calculate number of runes.

It will resolve most issues. But it don't take into account unicode text segmentation. So if there will be symbols such as emojis, that consists of more than one unicode character it still will calculate length incorrectly. More info could be found here.

So may be the next step is to add usage of https://github.com/rivo/uniseg. But considering it is a big change and new dependancy may be it is not worth it.

@danielgtaylor
Copy link
Owner

@maximdanilchenko thanks for the PR! This one is interesting to me because the length may be used to limit storage in e.g. a DB, so I wonder if we should be counting bytes, runes, or visible characters. It might be useful to give users the choice but that might also be overkill. I think counting runes is probably a good default.

Copy link

codecov bot commented Mar 12, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.07%. Comparing base (13acb69) to head (763b669).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #298   +/-   ##
=======================================
  Coverage   95.07%   95.07%           
=======================================
  Files          19       19           
  Lines        2742     2742           
=======================================
  Hits         2607     2607           
  Misses         98       98           
  Partials       37       37           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@x-user
Copy link
Contributor

x-user commented Mar 12, 2024

IMHO: it's used to validate input string length so it should count runes.

@danielgtaylor danielgtaylor merged commit 70b6550 into danielgtaylor:main Mar 13, 2024
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants