Skip to content

Commit 1c1a973

Browse files
committed
Add regex validator
1 parent 13b1958 commit 1c1a973

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

lib/validators/regex.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Regex validator
3+
*
4+
* {
5+
* regex: Regex
6+
* }
7+
*/
8+
9+
function isValid(data, model) {
10+
if (!model.regex) {
11+
return true;
12+
}
13+
14+
if(typeof model.regex === 'object' && typeof model.regex.test === 'function') {
15+
return model.regex.test(data);
16+
}
17+
18+
return false;
19+
}
20+
21+
22+
module.exports = isValid;

spec/validators/regex.spec.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
var valid = require('../../lib/validators/regex');
2+
3+
const regex = /[a]/;
4+
const validData = 'asd';
5+
const invalidData = 'sdf';
6+
7+
const model = {
8+
regex: regex
9+
};
10+
11+
describe(' - Regex validator', () => {
12+
it('shall be a function', () => {
13+
expect(typeof valid).toEqual('function');
14+
});
15+
16+
it('shall validate everything when no model set', () => {
17+
expect(valid(validData, {})).toEqual(true);
18+
expect(valid(invalidData, {})).toEqual(true);
19+
});
20+
21+
it('shall validate valid patterns when model set', () => {
22+
expect(valid(validData, model)).toEqual(true);
23+
});
24+
25+
it('shall not validate invalid patterns when model set', () => {
26+
expect(valid(invalidData, model)).toEqual(false);
27+
});
28+
});

0 commit comments

Comments
 (0)