/
RegExpValidation.ts
29 lines (25 loc) · 989 Bytes
/
RegExpValidation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { Result } from '../../Patterns/Result/Result';
import { IValidation } from '../../Patterns/Validator/IValidation';
import { Command } from '../../Patterns/CommandQuery/Command';
import { Model } from '../Model';
export class RegExpValidation<T> implements IValidation<Model<T>> {
constructor(
private member: string,
private regex: RegExp,
private customErrorMessage?: string
) { }
public Validate(object: Model<T>): Result<null> {
return new Command(() => {
const value = (object as any)[this.member];
const regex = new RegExp(this.regex);
const regexTestPasses = regex.test(value);
if (
!!value && // don't enforce if falsy - leave that to required validation
!regexTestPasses
) {
const label = object.LabelFor(this.member);
throw new Error(this.customErrorMessage || `${label} value: ${value} does not conform to the expected regular expression: ${regex}`);
}
}).Execute();
}
}