Skip to content

Commit 90e3ea8

Browse files
Add AnyOf assert
1 parent a90a45e commit 90e3ea8

6 files changed

Lines changed: 222 additions & 1 deletion

File tree

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ The following set of extra asserts are provided by this package:
2929
| Assert | Peer Dependency |
3030
| :------------------------------------------------------------------------------ | :--------------------------------------------------- |
3131
| [AbaRoutingNumber](#abaroutingnumber) | [`abavalidator`][abavalidator-url] |
32+
| [AnyOf](#anyof) | |
3233
| [BankIdentifierCode](#bankidentifiercode-bic) (_BIC_) | |
3334
| [BigNumber](#bignumber) | [`bignumber.js`][bignumber-url] |
3435
| [BigNumberEqualTo](#bignumberequalto) | [`bignumber.js`][bignumber-url] |
@@ -74,6 +75,14 @@ The following set of extra asserts are provided by this package:
7475

7576
Tests if the value is a valid [ABA Routing Number](http://www.accuity.com/PageFiles/255/ROUTING_NUMBER_POLICY.pdf).
7677

78+
### AnyOf
79+
80+
Tests if the value matches at least one of the provided constraint sets. Throws a violation if the value matches none of the constraint sets.
81+
82+
#### Arguments
83+
84+
- `...assertSets` (required) - two or more assert sets to test the value against. Each assert set must be a plain object mapping field names to arrays of asserts.
85+
7786
### BankIdentifierCode (_BIC_)
7887

7988
Tests if the value is a valid Bank Identifier Code (_BIC_) as defined in the [ISO-9362](http://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=60390) standard.

src/asserts/any-of-assert.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'use strict';
2+
3+
/**
4+
* Module dependencies.
5+
*/
6+
7+
const { Constraint, Violation } = require('validator.js');
8+
9+
/**
10+
* Export `AnyOfAssert`.
11+
*/
12+
13+
module.exports = function anyOfAssert(...assertSets) {
14+
/**
15+
* Class name.
16+
*/
17+
18+
this.__class__ = 'AnyOf';
19+
20+
if (assertSets.length < 2) {
21+
throw new Error('AnyOf constraint requires at least two assert sets');
22+
}
23+
24+
/**
25+
* Validation algorithm.
26+
*/
27+
28+
this.validate = value => {
29+
const violations = [];
30+
31+
for (const assertSet of assertSets) {
32+
const result = new Constraint(assertSet, { deepRequired: true }).check(value);
33+
34+
if (result === true) {
35+
return true;
36+
}
37+
38+
violations.push(result);
39+
}
40+
41+
throw new Violation(this, value, violations);
42+
};
43+
44+
return this;
45+
};

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
*/
66

77
const AbaRoutingNumber = require('./asserts/aba-routing-number-assert.js');
8+
const AnyOf = require('./asserts/any-of-assert.js');
89
const BankIdentifierCode = require('./asserts/bank-identifier-code-assert.js');
910
const BigNumber = require('./asserts/big-number-assert.js');
1011
const BigNumberEqualTo = require('./asserts/big-number-equal-to-assert.js');
@@ -52,6 +53,7 @@ const Uuid = require('./asserts/uuid-assert.js');
5253

5354
module.exports = {
5455
AbaRoutingNumber,
56+
AnyOf,
5557
BankIdentifierCode,
5658
BigNumber,
5759
BigNumberEqualTo,

src/types/index.d.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ interface AssertInstance {
1717
hasGroups(): boolean;
1818
}
1919

20+
/**
21+
* Constraint set.
22+
*/
23+
24+
export type ConstraintSet = AssertInstance | Array<AssertInstance> | { [key: string]: ConstraintSet };
25+
2026
/**
2127
* Core `validator.js-asserts` methods (lower-cased).
2228
*/
@@ -27,6 +33,9 @@ export interface ValidatorJSAsserts {
2733
*/
2834
abaRoutingNumber(): AssertInstance;
2935

36+
/** Value matches one or more of the provided constraint sets. */
37+
anyOf(...constraintSets: Array<ConstraintSet>): AssertInstance;
38+
3039
/** Valid BIC (Bank Identifier Code) used for international wire transfers. */
3140
bankIdentifierCode(): AssertInstance;
3241

test/asserts/any-of-assert.test.js

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
'use strict';
2+
3+
/**
4+
* Module dependencies.
5+
*/
6+
7+
const { Assert: BaseAssert, Violation } = require('validator.js');
8+
const { describe, it } = require('node:test');
9+
const AnyOfAssert = require('../../src/asserts/any-of-assert.js');
10+
11+
/**
12+
* Extend `Assert` with `AnyOfAssert`.
13+
*/
14+
15+
const Assert = BaseAssert.extend({
16+
AnyOf: AnyOfAssert
17+
});
18+
19+
/**
20+
* Test `AnyOfAssert`.
21+
*/
22+
23+
describe('AnyOfAssert', () => {
24+
it('should throw an error if no constraint sets are provided', ({ assert }) => {
25+
try {
26+
Assert.anyOf();
27+
28+
assert.fail();
29+
} catch (e) {
30+
assert.equal(e.message, 'AnyOf constraint requires at least two assert sets');
31+
}
32+
});
33+
34+
it('should throw an error if only one constraint set is provided', ({ assert }) => {
35+
try {
36+
Assert.anyOf({ bar: [Assert.equalTo('foo')] });
37+
38+
assert.fail();
39+
} catch (e) {
40+
assert.equal(e.message, 'AnyOf constraint requires at least two assert sets');
41+
}
42+
});
43+
44+
it('should throw an error if value does not match any constraint set', ({ assert }) => {
45+
try {
46+
Assert.anyOf({ bar: [Assert.equalTo('foo')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'biz' });
47+
48+
assert.fail();
49+
} catch (e) {
50+
assert.ok(e instanceof Violation);
51+
assert.equal(e.show().assert, 'AnyOf');
52+
}
53+
});
54+
55+
it('should include all violations in the error when no constraint set matches', ({ assert }) => {
56+
try {
57+
Assert.anyOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'qux' });
58+
59+
assert.fail();
60+
} catch (e) {
61+
const { violation } = e.show();
62+
63+
assert.equal(violation.length, 2);
64+
assert.ok(violation[0].bar[0] instanceof Violation);
65+
assert.equal(violation[0].bar[0].show().assert, 'EqualTo');
66+
assert.equal(violation[0].bar[0].show().violation.value, 'biz');
67+
assert.ok(violation[1].bar[0] instanceof Violation);
68+
assert.equal(violation[1].bar[0].show().assert, 'EqualTo');
69+
assert.equal(violation[1].bar[0].show().violation.value, 'baz');
70+
}
71+
});
72+
73+
it('should validate required fields using `deepRequired`', ({ assert }) => {
74+
try {
75+
Assert.anyOf(
76+
{ bar: [Assert.required(), Assert.notBlank()] },
77+
{ baz: [Assert.required(), Assert.notBlank()] }
78+
).validate({});
79+
80+
assert.fail();
81+
} catch (e) {
82+
assert.ok(e instanceof Violation);
83+
assert.equal(e.show().assert, 'AnyOf');
84+
}
85+
});
86+
87+
it('should throw an error if a constraint set with an extra assert does not match', ({ assert }) => {
88+
try {
89+
Assert.anyOf(
90+
{
91+
bar: [Assert.equalTo('biz')],
92+
baz: [Assert.anyOf({ qux: [Assert.equalTo('corge')] }, { qux: [Assert.equalTo('grault')] })]
93+
},
94+
{ bar: [Assert.equalTo('baz')] }
95+
).validate({ bar: 'biz', baz: { qux: 'wrong' } });
96+
97+
assert.fail();
98+
} catch (e) {
99+
assert.ok(e instanceof Violation);
100+
assert.equal(e.show().assert, 'AnyOf');
101+
}
102+
});
103+
104+
it('should pass if a constraint set contains either a required field or an optional field', ({ assert }) => {
105+
assert.doesNotThrow(() => {
106+
Assert.anyOf({ bar: [Assert.required(), Assert.notBlank()] }, { baz: Assert.notBlank() }).validate({});
107+
});
108+
});
109+
110+
it('should pass if value matches more than one constraint set', ({ assert }) => {
111+
assert.doesNotThrow(() => {
112+
Assert.anyOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('biz')] }).validate({ bar: 'biz' });
113+
});
114+
});
115+
116+
it('should pass if value matches more than one constraint set with different constraints', ({ assert }) => {
117+
assert.doesNotThrow(() => {
118+
Assert.anyOf({ bar: [Assert.notBlank()] }, { bar: [Assert.equalTo('biz')] }).validate({ bar: 'biz' });
119+
});
120+
});
121+
122+
it('should pass if value matches the first constraint set', ({ assert }) => {
123+
assert.doesNotThrow(() => {
124+
Assert.anyOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'biz' });
125+
});
126+
});
127+
128+
it('should pass if value matches the second constraint set', ({ assert }) => {
129+
assert.doesNotThrow(() => {
130+
Assert.anyOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'baz' });
131+
});
132+
});
133+
134+
it('should support more than two constraint sets', ({ assert }) => {
135+
assert.doesNotThrow(() => {
136+
Assert.anyOf(
137+
{ bar: [Assert.equalTo('biz')] },
138+
{ bar: [Assert.equalTo('baz')] },
139+
{ bar: [Assert.equalTo('qux')] }
140+
).validate({ bar: 'qux' });
141+
});
142+
});
143+
144+
it('should pass if a constraint set contains an extra assert', ({ assert }) => {
145+
assert.doesNotThrow(() => {
146+
Assert.anyOf(
147+
{
148+
bar: [Assert.equalTo('biz')],
149+
baz: [Assert.anyOf({ qux: [Assert.equalTo('corge')] }, { qux: [Assert.equalTo('grault')] })]
150+
},
151+
{ bar: [Assert.equalTo('baz')] }
152+
).validate({ bar: 'biz', baz: { qux: 'corge' } });
153+
});
154+
});
155+
});

test/index.test.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@ describe('validator.js-asserts', () => {
1515
it('should export all asserts', ({ assert }) => {
1616
const assertNames = Object.keys(asserts);
1717

18-
assert.equal(assertNames.length, 41);
18+
assert.equal(assertNames.length, 42);
1919
assert.deepEqual(assertNames, [
2020
'AbaRoutingNumber',
21+
'AnyOf',
2122
'BankIdentifierCode',
2223
'BigNumber',
2324
'BigNumberEqualTo',

0 commit comments

Comments
 (0)