Skip to content

Commit

Permalink
Add RegEx validation for @pattern decorator (microsoft#5252)
Browse files Browse the repository at this point in the history
... and throw a warning for invalid regex string value.

close microsoft#4128
  • Loading branch information
allenjzhang authored and Mingzhe Huang (from Dev Box) committed Dec 17, 2024
1 parent 6c4b8cc commit 2000802
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/compiler"
---

Added RegEx validation for @pattern and will throw warning for invalid RegEx string
7 changes: 7 additions & 0 deletions packages/compiler/src/core/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,13 @@ const diagnostics = {
/**
* Decorator
*/
"invalid-pattern-regex": {
severity: "warning",
messages: {
default: "@pattern decorator expects a valid regular expression pattern.",
},
},

"decorator-wrong-target": {
severity: "error",
messages: {
Expand Down
8 changes: 8 additions & 0 deletions packages/compiler/src/lib/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,14 @@ export const $pattern: PatternDecorator = (
return;
}

try {
new RegExp(pattern);
} catch (e) {
reportDiagnostic(context.program, {
code: "invalid-pattern-regex",
target: target,
});
}
const patternData: PatternData = {
pattern,
validationMessage,
Expand Down
13 changes: 13 additions & 0 deletions packages/compiler/test/decorators/decorators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,19 @@ describe("compiler: built-in decorators", () => {
});
});

it("emit diagnostic if pattern is not a valid RegEx", async () => {
const diagnostics = await runner.diagnose(`
model A {
@pattern("[a-z")
prop: string;
}
`);

expectDiagnostics(diagnostics, {
code: "invalid-pattern-regex",
});
});

it("optionally allows specifying a pattern validation message", async () => {
const { A, B } = (await runner.compile(
`
Expand Down

0 comments on commit 2000802

Please sign in to comment.