Skip to content

Commit

Permalink
fix: correctly run .matches when passing regex object (#1156)
Browse files Browse the repository at this point in the history
  • Loading branch information
tonysamperi committed Jun 19, 2022
1 parent 82e4d84 commit 6b2edda
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
53 changes: 53 additions & 0 deletions src/chain/validators-impl.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import * as validator from 'validator';
import { Meta } from '../base';
import { CustomValidation, StandardValidation } from '../context-items';
import { ContextBuilder } from '../context-builder';
import { body } from '../middlewares/validation-chain-builders';
import { validationResult } from '../validation-result';
import { Validators } from './validators';
import { ValidatorsImpl } from './validators-impl';

Expand Down Expand Up @@ -363,3 +365,54 @@ describe('#notEmpty()', () => {
);
});
});

describe('correctly merges validator.matches flags', () => {
it('correctly uses modifiers and string', () => {
validators.matches('baz', 'gi');
expect(builder.addItem).toHaveBeenCalledWith(
new StandardValidation(validator.matches, false, ['baz', 'gi']),
);
});

it('correctly uses modifiers and regex flags', () => {
validators.matches(/baz/gi, 'm');
expect(builder.addItem).toHaveBeenCalledWith(
new StandardValidation(validator.matches, false, ['baz', 'mgi']),
);
});
});

describe('always correctly validates with validator.matches using the g flag', () => {
const expectedErr = {
value: 'fo157115',
msg: 'INVALID USER FORMAT',
param: 'user',
location: 'body',
};
[
{ name: 'with valid value', user: 'it157115', expected: [] },
{
name: 'with invalid value',
user: 'fo157115',
expected: [expectedErr, expectedErr, expectedErr],
},
].forEach(config => {
it(config.name, async () => {
const req = { body: { user: config.user } };
const validator = body('user')
.toLowerCase()
.matches(/^(it)(\d{6})$/g)
.withMessage('INVALID USER FORMAT');

// try three times because per #1127 validation failed one other time
let i = 0;
const results = [];
while (++i < 3) {
await validator.run(req);
results.push(...validationResult(req).array());
}

expect(results).toEqual(config.expected);
});
});
});
7 changes: 6 additions & 1 deletion src/chain/validators-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,11 @@ export class ValidatorsImpl<Chain> implements Validators<Chain> {
return this.addStandardValidation(validator.isWhitelisted, chars);
}
matches(pattern: RegExp | string, modifiers?: string) {
return this.addStandardValidation(validator.matches, pattern, modifiers);
return this.addStandardValidation.apply(this, [
validator.matches,
...(typeof pattern === 'string'
? [pattern, modifiers]
: [pattern.source, [...new Set((modifiers || '') + pattern.flags)].join('')]),
]);
}
}

0 comments on commit 6b2edda

Please sign in to comment.