Skip to content

Commit

Permalink
Merge pull request #10 from fullstacksjs/feat/regex-validation
Browse files Browse the repository at this point in the history
feat: regex validation
  • Loading branch information
ASafaeirad authored Jun 26, 2024
2 parents 8781a8a + 58e3162 commit 9e538cd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Schema/StringSchema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,15 @@ describe('String Schema', () => {

expect(() => schema.validate()).not.toThrow();
});

it('should throw when regex does not match', () => {
const schema = new StringSchema().regex(/\d+/).setValue('a');
schema.key = 'port';

expect(() => schema.validate()).toThrow(
new TypeError(
`Invalid configuration: The "port" expected to follow "${String(/\d+/)}" regex but received "a"`,
),
);
});
});
16 changes: 16 additions & 0 deletions src/Schema/StringSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ class MaxLengthGuard implements Guard<string> {
}
}

class RegExGuard implements Guard<string> {
constructor(private regex: RegExp) {}

validate(input: string, field: string) {
if (!this.regex.test(input))
throw new RangeError(
`Invalid configuration: The "${field}" expected to follow "${this.regex}" regex but received "${input}"`,
);
}
}

export class StringSchema<TInput = any> extends Schema<TInput, string> {
protected type = 'string';

Expand All @@ -45,4 +56,9 @@ export class StringSchema<TInput = any> extends Schema<TInput, string> {
this.guards.push(new MaxLengthGuard(max));
return this;
}

public regex(regex: RegExp) {
this.guards.push(new RegExGuard(regex));
return this;
}
}

0 comments on commit 9e538cd

Please sign in to comment.