Skip to content

Commit 3dcd93d

Browse files
adamthom-amznsrchase
authored andcommitted
Fix the implementation of length validation for strings
The Smithy spec specifies that string length is defined as the number of code points. JavaScript's String.length returns the number of code units, leading to inaccurate validation when a string contains characters that use multiple code units to represent one code point. Fixes smithy-lang#509
1 parent 1e05730 commit 3dcd93d

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

smithy-typescript-ssdk-libs/server-common/src/validation/validators.spec.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,10 @@ describe("length validation", () => {
114114
});
115115
});
116116
}
117+
118+
it("properly assesses string length", () => {
119+
expect(new LengthValidator(3, 3).validate("👍👍👍", "threeEmojis")).toBeNull();
120+
});
117121
});
118122

119123
describe("pattern validation", () => {

smithy-typescript-ssdk-libs/server-common/src/validation/validators.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ export class EnumValidator implements SingleConstraintValidator<string, EnumVali
174174
}
175175
}
176176

177-
type LengthCheckable = { length: number } | { [key: string]: any };
177+
type LengthCheckable = string | { length: number } | { [key: string]: any };
178178

179179
export class LengthValidator implements SingleConstraintValidator<LengthCheckable, LengthValidationFailure> {
180180
private readonly min?: number;
@@ -194,7 +194,9 @@ export class LengthValidator implements SingleConstraintValidator<LengthCheckabl
194194
}
195195

196196
let length: number;
197-
if (LengthValidator.hasLength(input)) {
197+
if (typeof input === "string") {
198+
length = [...input].length; // string length is defined by the number of code points
199+
} else if (LengthValidator.hasLength(input)) {
198200
length = input.length;
199201
} else {
200202
length = Object.keys(input).length;

0 commit comments

Comments
 (0)