Skip to content

Commit 2df471c

Browse files
committed
feat: add regex rule to StringValidator
1 parent 976f6be commit 2df471c

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/validation/reporter.spec.ts

+27
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,33 @@ describe('Reporter', () => {
201201
expect(errors[0]).toBe(message);
202202
}
203203
});
204+
205+
it('should report an error when string does not match specified regex', () => {
206+
interface S {
207+
s1: string;
208+
}
209+
interface T {
210+
t1: string;
211+
}
212+
213+
const REGEX = /^[0-9]+$/;
214+
const VALUE = 'aaa';
215+
const schema = createSchema<T, S>({
216+
t1: {
217+
fn: value => value.s1,
218+
validation: Validation.string().regex(REGEX)
219+
}
220+
});
221+
const result = morphism(schema, { s1: VALUE });
222+
const error = new ValidationError({ targetProperty: 't1', expect: `value to match pattern: ${REGEX}`, value: VALUE });
223+
const message = defaultFormatter(error);
224+
const errors = reporter.report(result);
225+
expect(errors).not.toBeNull();
226+
if (errors) {
227+
expect(errors.length).toEqual(1);
228+
expect(errors[0]).toBe(message);
229+
}
230+
});
204231
});
205232

206233
describe('number', () => {

src/validation/validators/StringValidator.ts

+13
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,17 @@ export class StringValidator extends BaseValidator<string> {
5656
});
5757
return this;
5858
}
59+
regex(regex: RegExp) {
60+
this.addRule({
61+
name: 'regex',
62+
expect: `value to match pattern: ${regex}`,
63+
test: function(value) {
64+
if (!regex.test(value)) {
65+
throw new ValidatorError({ value, expect: this.expect });
66+
}
67+
return value;
68+
}
69+
});
70+
return this;
71+
}
5972
}

0 commit comments

Comments
 (0)