Skip to content

Commit a6d3ee8

Browse files
authored
Merge pull request #17 from stolen/string-length-in-code-points
openapi_schema: count UTF8 code points when checking string length constraints
2 parents 0a292a1 + 3ba37b4 commit a6d3ee8

2 files changed

Lines changed: 18 additions & 6 deletions

File tree

src/openapi_schema.erl

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -486,11 +486,12 @@ encode3(#{type := <<"string">>} = Spec, #{auto_convert := Convert} = Options, In
486486
{error, _} ->
487487
Input1;
488488
_ ->
489+
Length = string:length(InputForValidation),
489490
case Spec of
490-
#{minLength := MinLength} when size(InputForValidation) < MinLength ->
491-
{error, #{error => too_short, path => Path, input => Input, detail => length(Input), min_length => MinLength}};
492-
#{maxLength := MaxLength} when size(InputForValidation) > MaxLength ->
493-
{error, #{error => too_long, path => Path, input => Input, detail => length(Input), max_length => MaxLength}};
491+
#{minLength := MinLength} when Length < MinLength ->
492+
{error, #{error => too_short, path => Path, input => Input, detail => Length, min_length => MinLength}};
493+
#{maxLength := MaxLength} when Length > MaxLength ->
494+
{error, #{error => too_long, path => Path, input => Input, detail => Length, max_length => MaxLength}};
494495
#{} ->
495496
Format = maps:get(format, Spec, undefined),
496497
Validators = maps:get(validators, Options),

test/openapi_schema_SUITE.erl

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,10 +333,21 @@ external_validators(_) ->
333333

334334

335335
min_max_length(_) ->
336-
{error, #{error := too_short}} =
336+
{error, #{error := too_short, detail := 3}} =
337337
openapi_schema:process(<<"123">>, #{schema => #{type => <<"string">>, minLength => 5}}),
338-
{error, #{error := too_long}} =
338+
{error, #{error := too_long, detail := 3}} =
339339
openapi_schema:process(<<"123">>, #{schema => #{type => <<"string">>, maxLength => 2}}),
340+
341+
{error, #{error := too_short, detail := 4}} =
342+
openapi_schema:process(atom, #{schema => #{type => <<"string">>, minLength => 5}}),
343+
{error, #{error := too_long, detail := 4}} =
344+
openapi_schema:process(atom, #{schema => #{type => <<"string">>, maxLength => 2}}),
345+
346+
UTFString = unicode:characters_to_binary([128578,128579]), % 2 code points, but 8 bytes
347+
{error, #{error := too_short, detail := 2}} =
348+
openapi_schema:process(UTFString, #{schema => #{type => <<"string">>, minLength => 3}}),
349+
{error, #{error := too_long, detail := 2}} =
350+
openapi_schema:process(UTFString, #{schema => #{type => <<"string">>, maxLength => 1}}),
340351
ok.
341352

342353

0 commit comments

Comments
 (0)