Skip to content

Commit b00ecb2

Browse files
committed
fix(zmodel): validate @regex regular expression patterns
1 parent 54a9b21 commit b00ecb2

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

packages/schema/src/language-server/validator/attribute-application-validator.ts

+15
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,21 @@ export default class AttributeApplicationValidator implements AstValidator<Attri
212212
}
213213
}
214214

215+
@check('@regex')
216+
private _checkRegex(attr: AttributeApplication, accept: ValidationAcceptor) {
217+
const regex = getStringLiteral(attr.args[0]?.value);
218+
if (regex === undefined) {
219+
accept('error', `Expecting a string literal`, { node: attr.args[0] ?? attr });
220+
return;
221+
}
222+
223+
try {
224+
new RegExp(regex);
225+
} catch (e) {
226+
accept('error', `${e}`, { node: attr.args[0] });
227+
}
228+
}
229+
215230
private rejectEncryptedFields(attr: AttributeApplication, accept: ValidationAcceptor) {
216231
streamAllContents(attr).forEach((node) => {
217232
if (isDataModelFieldReference(node) && hasAttribute(node.target.ref as DataModelField, '@encrypted')) {

packages/schema/tests/schema/validation/attribute-validation.test.ts

+22
Original file line numberDiff line numberDiff line change
@@ -1369,4 +1369,26 @@ describe('Attribute tests', () => {
13691369
`)
13701370
).resolves.toContain(`attribute "@omit" cannot be used on type declaration fields`);
13711371
});
1372+
1373+
it('validates regex', async () => {
1374+
await expect(
1375+
loadModelWithError(`
1376+
${prelude}
1377+
model User {
1378+
id String @id
1379+
phone String @regex(id)
1380+
}
1381+
`)
1382+
).resolves.toContain('Expecting a string literal');
1383+
1384+
await expect(
1385+
loadModelWithError(`
1386+
${prelude}
1387+
model User {
1388+
id String @id
1389+
phone String @regex("^(\\+46|0)[0-9]{7,12}$")
1390+
}
1391+
`)
1392+
).resolves.toContain('Invalid regular expression');
1393+
});
13721394
});

0 commit comments

Comments
 (0)