Skip to content

Commit

Permalink
feat: add alphanum rule to StringValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
emyann committed Jul 26, 2019
1 parent 2df471c commit bcf66c1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
26 changes: 26 additions & 0 deletions src/validation/reporter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,32 @@ describe('Reporter', () => {
expect(errors[0]).toBe(message);
}
});

it('should report an error when string does not match alphanum rule', () => {
interface S {
s1: string;
}
interface T {
t1: string;
}

const VALUE = '(*&@#$)';
const schema = createSchema<T, S>({
t1: {
fn: value => value.s1,
validation: Validation.string().alphanum()
}
});
const result = morphism(schema, { s1: VALUE });
const error = new ValidationError({ targetProperty: 't1', expect: `value to contain only alphanumeric characters`, value: VALUE });
const message = defaultFormatter(error);
const errors = reporter.report(result);
expect(errors).not.toBeNull();
if (errors) {
expect(errors.length).toEqual(1);
expect(errors[0]).toBe(message);
}
});
});

describe('number', () => {
Expand Down
22 changes: 16 additions & 6 deletions src/validation/validators/StringValidator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BaseValidator } from './BaseValidator';
import { BaseValidator, Rule } from './BaseValidator';
import { isString } from '../../helpers';
import { ValidatorError } from './ValidatorError';

Expand Down Expand Up @@ -56,17 +56,27 @@ export class StringValidator extends BaseValidator<string> {
});
return this;
}
regex(regex: RegExp) {
this.addRule({
name: 'regex',
expect: `value to match pattern: ${regex}`,
private createRegexRule(name: string, expect: string, regex: RegExp): Rule<string> {
return {
name,
expect,
test: function(value) {
if (!regex.test(value)) {
throw new ValidatorError({ value, expect: this.expect });
}
return value;
}
});
};
}
regex(regex: RegExp) {
const rule = this.createRegexRule('regex', `value to match pattern: ${regex}`, regex);
this.addRule(rule);
return this;
}

alphanum() {
const rule = this.createRegexRule('regex', `value to contain only alphanumeric characters`, /^[a-z0-9]+$/i);
this.addRule(rule);
return this;
}
}

0 comments on commit bcf66c1

Please sign in to comment.