Skip to content

Commit a226a76

Browse files
authored
Add RegEx validation for @pattern decorator (microsoft#5252)
... and throw a warning for invalid regex string value. close microsoft#4128
1 parent a3e1c54 commit a226a76

File tree

4 files changed

+35
-0
lines changed

4 files changed

+35
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
changeKind: fix
3+
packages:
4+
- "@typespec/compiler"
5+
---
6+
7+
Added RegEx validation for @pattern and will throw warning for invalid RegEx string

packages/compiler/src/core/messages.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,13 @@ const diagnostics = {
781781
/**
782782
* Decorator
783783
*/
784+
"invalid-pattern-regex": {
785+
severity: "warning",
786+
messages: {
787+
default: "@pattern decorator expects a valid regular expression pattern.",
788+
},
789+
},
790+
784791
"decorator-wrong-target": {
785792
severity: "error",
786793
messages: {

packages/compiler/src/lib/decorators.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,14 @@ export const $pattern: PatternDecorator = (
414414
return;
415415
}
416416

417+
try {
418+
new RegExp(pattern);
419+
} catch (e) {
420+
reportDiagnostic(context.program, {
421+
code: "invalid-pattern-regex",
422+
target: target,
423+
});
424+
}
417425
const patternData: PatternData = {
418426
pattern,
419427
validationMessage,

packages/compiler/test/decorators/decorators.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,19 @@ describe("compiler: built-in decorators", () => {
261261
});
262262
});
263263

264+
it("emit diagnostic if pattern is not a valid RegEx", async () => {
265+
const diagnostics = await runner.diagnose(`
266+
model A {
267+
@pattern("[a-z")
268+
prop: string;
269+
}
270+
`);
271+
272+
expectDiagnostics(diagnostics, {
273+
code: "invalid-pattern-regex",
274+
});
275+
});
276+
264277
it("optionally allows specifying a pattern validation message", async () => {
265278
const { A, B } = (await runner.compile(
266279
`

0 commit comments

Comments
 (0)