Skip to content

Commit 7ae2de3

Browse files
Add OneOf assert
1 parent 26ecd42 commit 7ae2de3

6 files changed

Lines changed: 231 additions & 1 deletion

File tree

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ The following set of extra asserts are provided by this package:
6060
| [NullOrBoolean](#nullorboolean) | |
6161
| [NullOrDate](#nullordate) | |
6262
| [NullOrString](#nullorstring) | |
63+
| [OneOf](#oneof) | |
6364
| [Phone](#phone) | [`google-libphonenumber`][google-libphonenumber-url] |
6465
| [PlainObject](#plainobject) | |
6566
| [RfcNumber](#rfcnumber) | [`validate-rfc`][validate-rfc-url] |
@@ -276,6 +277,14 @@ Tests if the value is a `null` or `string`, optionally within some boundaries.
276277

277278
- `boundaries` (optional) - `max` and/or `min` boundaries to test the string for.
278279

280+
### OneOf
281+
282+
Tests if the value matches exactly one of the provided assert sets. Throws a violation if the value matches none or more than one assert set.
283+
284+
#### Arguments
285+
286+
- `...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.
287+
279288
### Phone
280289

281290
Tests if the phone is valid and optionally if it belongs to the given country. The phone can be in the national or E164 formats.

src/asserts/one-of-assert.js

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

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ const NullOr = require('./asserts/null-or-assert.js');
3636
const NullOrBoolean = require('./asserts/null-or-boolean-assert.js');
3737
const NullOrDate = require('./asserts/null-or-date-assert.js');
3838
const NullOrString = require('./asserts/null-or-string-assert.js');
39+
const OneOf = require('./asserts/one-of-assert.js');
3940
const Phone = require('./asserts/phone-assert.js');
4041
const PlainObject = require('./asserts/plain-object-assert.js');
4142
const RfcNumber = require('./asserts/rfc-number-assert.js');
@@ -83,6 +84,7 @@ module.exports = {
8384
NullOrBoolean,
8485
NullOrDate,
8586
NullOrString,
87+
OneOf,
8688
Phone,
8789
PlainObject,
8890
RfcNumber,

src/types/index.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,9 @@ export interface ValidatorJSAsserts {
170170
/** Value is null or a string (length within `[min, max]`). */
171171
nullOrString(boundaries?: { min?: number; max?: number }): AssertInstance;
172172

173+
/** Value matches exactly one of the provided constraint sets. */
174+
oneOf(...assertSets: Array<{ [key: string]: AssertInstance | Array<AssertInstance> }>): AssertInstance;
175+
173176
/** Valid phone number (optionally by country code). @requires google-libphonenumber */
174177
phone(options?: { countryCode?: string }): AssertInstance;
175178

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

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
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 OneOfAssert = require('../../src/asserts/one-of-assert.js');
10+
11+
/**
12+
* Extend `Assert` with `OneOfAssert`.
13+
*/
14+
15+
const Assert = BaseAssert.extend({
16+
OneOf: OneOfAssert
17+
});
18+
19+
/**
20+
* Test `OneOfAssert`.
21+
*/
22+
23+
describe('OneOfAssert', () => {
24+
it('should throw an error if no constraint sets are provided', ({ assert }) => {
25+
try {
26+
Assert.oneOf();
27+
28+
assert.fail();
29+
} catch (e) {
30+
assert.equal(e.message, 'OneOf assert requires at least two constraint sets');
31+
}
32+
});
33+
34+
it('should throw an error if only one constraint set is provided', ({ assert }) => {
35+
try {
36+
Assert.oneOf({ bar: [Assert.equalTo('foo')] });
37+
38+
assert.fail();
39+
} catch (e) {
40+
assert.equal(e.message, 'OneOf assert requires at least two constraint sets');
41+
}
42+
});
43+
44+
it('should throw an error if value does not match any constraint set', ({ assert }) => {
45+
try {
46+
Assert.oneOf({ 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, 'OneOf');
52+
}
53+
});
54+
55+
it('should include all violations in the error when no constraint set matches', ({ assert }) => {
56+
try {
57+
Assert.oneOf({ 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.oneOf(
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, 'OneOf');
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.oneOf(
90+
{
91+
bar: [Assert.equalTo('biz')],
92+
baz: [Assert.oneOf({ 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, 'OneOf');
101+
}
102+
});
103+
104+
it('should throw an error if value matches more than one constraint set', ({ assert }) => {
105+
try {
106+
Assert.oneOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('biz')] }).validate({ bar: 'biz' });
107+
108+
assert.fail();
109+
} catch (e) {
110+
const { violation } = e.show();
111+
112+
assert.ok(e instanceof Violation);
113+
assert.equal(e.show().assert, 'OneOf');
114+
assert.equal(violation.length, 1);
115+
assert.ok(violation[0] instanceof Violation);
116+
assert.equal(violation[0].show().violation.value, 'more_than_one_constraint_set_matched');
117+
}
118+
});
119+
120+
it('should throw an error if value matches more than one constraint set with overlapping schemas', ({ assert }) => {
121+
try {
122+
Assert.oneOf({ bar: [Assert.notBlank()] }, { bar: [Assert.equalTo('biz')] }).validate({ bar: 'biz' });
123+
124+
assert.fail();
125+
} catch (e) {
126+
const { violation } = e.show();
127+
128+
assert.ok(e instanceof Violation);
129+
assert.equal(e.show().assert, 'OneOf');
130+
assert.equal(violation.length, 1);
131+
assert.ok(violation[0] instanceof Violation);
132+
assert.equal(violation[0].show().violation.value, 'more_than_one_constraint_set_matched');
133+
}
134+
});
135+
136+
it('should pass if value matches the first constraint set', ({ assert }) => {
137+
assert.doesNotThrow(() => {
138+
Assert.oneOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'biz' });
139+
});
140+
});
141+
142+
it('should pass if value matches the second constraint set', ({ assert }) => {
143+
assert.doesNotThrow(() => {
144+
Assert.oneOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'baz' });
145+
});
146+
});
147+
148+
it('should support more than two constraint sets', ({ assert }) => {
149+
assert.doesNotThrow(() => {
150+
Assert.oneOf(
151+
{ bar: [Assert.equalTo('biz')] },
152+
{ bar: [Assert.equalTo('baz')] },
153+
{ bar: [Assert.equalTo('qux')] }
154+
).validate({ bar: 'qux' });
155+
});
156+
});
157+
158+
it('should pass if a constraint set contains an extra assert', ({ assert }) => {
159+
assert.doesNotThrow(() => {
160+
Assert.oneOf(
161+
{
162+
bar: [Assert.equalTo('biz')],
163+
baz: [Assert.oneOf({ qux: [Assert.equalTo('corge')] }, { qux: [Assert.equalTo('grault')] })]
164+
},
165+
{ bar: [Assert.equalTo('baz')] }
166+
).validate({ bar: 'biz', baz: { qux: 'corge' } });
167+
});
168+
});
169+
});

test/index.test.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ 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',
2121
'BankIdentifierCode',
@@ -49,6 +49,7 @@ describe('validator.js-asserts', () => {
4949
'NullOrBoolean',
5050
'NullOrDate',
5151
'NullOrString',
52+
'OneOf',
5253
'Phone',
5354
'PlainObject',
5455
'RfcNumber',

0 commit comments

Comments
 (0)