Skip to content

Commit 039afc7

Browse files
Add OneOf assert
1 parent ee4e5ad commit 039afc7

6 files changed

Lines changed: 218 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 constraint sets. Throws a violation if the value matches none or more than one constraint set.
283+
284+
#### Arguments
285+
286+
- `...constraintSets` (required) - two or more constraint set objects to test the value against.
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: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
'use strict';
2+
3+
/**
4+
* Module dependencies.
5+
*/
6+
7+
const { Constraint, Validator, Violation } = require('validator.js');
8+
9+
/**
10+
* Export `OneOfAssert`.
11+
*/
12+
13+
module.exports = function oneOfAssert(...constraintSets) {
14+
if (constraintSets.length < 2) {
15+
throw new Error('OneOf constraint requires at least two constraint sets');
16+
}
17+
18+
/**
19+
* Class name.
20+
*/
21+
22+
this.__class__ = 'OneOf';
23+
24+
/**
25+
* Validation algorithm.
26+
*/
27+
28+
this.validate = value => {
29+
const validator = new Validator();
30+
const matches = [];
31+
const violations = [];
32+
33+
for (const constraintSet of constraintSets) {
34+
const result = validator.validate(value, new Constraint(constraintSet, { deepRequired: true }));
35+
36+
if (result === true) {
37+
matches.push(constraintSet);
38+
} else {
39+
violations.push(result);
40+
}
41+
}
42+
43+
if (matches.length === 1) {
44+
return true;
45+
}
46+
47+
throw new Violation(this, value, matches.length > 1 ? { matches: matches.length } : violations);
48+
};
49+
50+
return this;
51+
};

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 at least one of the provided constraint sets. */
174+
oneOf(...constraintSets: Record<string, 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: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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+
assert.throws(() => Assert.oneOf(), { message: 'OneOf constraint requires at least two constraint sets' });
26+
});
27+
28+
it('should throw an error if only one constraint set is provided', ({ assert }) => {
29+
assert.throws(() => Assert.oneOf({ bar: [Assert.equalTo('foo')] }), {
30+
message: 'OneOf constraint requires at least two constraint sets'
31+
});
32+
});
33+
34+
it('should throw an error if value does not match any constraint set', ({ assert }) => {
35+
try {
36+
Assert.oneOf({ bar: [Assert.equalTo('foo')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'biz' });
37+
38+
assert.fail();
39+
} catch (e) {
40+
assert.ok(e instanceof Violation);
41+
assert.equal(e.show().assert, 'OneOf');
42+
}
43+
});
44+
45+
it('should include all violations in the error when no constraint set matches', ({ assert }) => {
46+
try {
47+
Assert.oneOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'qux' });
48+
49+
assert.fail();
50+
} catch (e) {
51+
const { violation } = e.show();
52+
53+
assert.equal(violation.length, 2);
54+
assert.ok(violation[0].bar[0] instanceof Violation);
55+
assert.equal(violation[0].bar[0].show().assert, 'EqualTo');
56+
assert.equal(violation[0].bar[0].show().violation.value, 'biz');
57+
assert.ok(violation[1].bar[0] instanceof Violation);
58+
assert.equal(violation[1].bar[0].show().assert, 'EqualTo');
59+
assert.equal(violation[1].bar[0].show().violation.value, 'baz');
60+
}
61+
});
62+
63+
it('should validate required fields using `deepRequired`', ({ assert }) => {
64+
try {
65+
Assert.oneOf(
66+
{ bar: [Assert.required(), Assert.notBlank()] },
67+
{ baz: [Assert.required(), Assert.notBlank()] }
68+
).validate({});
69+
70+
assert.fail();
71+
} catch (e) {
72+
assert.ok(e instanceof Violation);
73+
assert.equal(e.show().assert, 'OneOf');
74+
}
75+
});
76+
77+
it('should throw an error if a constraint set with an extra assert does not match', ({ assert }) => {
78+
try {
79+
Assert.oneOf(
80+
{
81+
bar: [Assert.equalTo('biz')],
82+
baz: [Assert.oneOf({ qux: [Assert.equalTo('corge')] }, { qux: [Assert.equalTo('grault')] })]
83+
},
84+
{ bar: [Assert.equalTo('baz')] }
85+
).validate({ bar: 'biz', baz: { qux: 'wrong' } });
86+
87+
assert.fail();
88+
} catch (e) {
89+
assert.ok(e instanceof Violation);
90+
assert.equal(e.show().assert, 'OneOf');
91+
}
92+
});
93+
94+
it('should throw an error if value matches more than one constraint set', ({ assert }) => {
95+
try {
96+
Assert.oneOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('biz')] }).validate({ bar: 'biz' });
97+
98+
assert.fail();
99+
} catch (e) {
100+
assert.ok(e instanceof Violation);
101+
assert.equal(e.show().assert, 'OneOf');
102+
assert.deepStrictEqual(e.show().violation, { matches: 2 });
103+
}
104+
});
105+
106+
it('should throw an error if value matches more than one constraint set with overlapping schemas', ({ assert }) => {
107+
try {
108+
Assert.oneOf({ bar: [Assert.notBlank()] }, { bar: [Assert.equalTo('biz')] }).validate({ bar: 'biz' });
109+
110+
assert.fail();
111+
} catch (e) {
112+
assert.ok(e instanceof Violation);
113+
assert.equal(e.show().assert, 'OneOf');
114+
assert.deepStrictEqual(e.show().violation, { matches: 2 });
115+
}
116+
});
117+
118+
it('should pass if value matches the first constraint set', ({ assert }) => {
119+
assert.doesNotThrow(() => {
120+
Assert.oneOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'biz' });
121+
});
122+
});
123+
124+
it('should pass if value matches the second constraint set', ({ assert }) => {
125+
assert.doesNotThrow(() => {
126+
Assert.oneOf({ bar: [Assert.equalTo('biz')] }, { bar: [Assert.equalTo('baz')] }).validate({ bar: 'baz' });
127+
});
128+
});
129+
130+
it('should support more than two constraint sets', ({ assert }) => {
131+
assert.doesNotThrow(() => {
132+
Assert.oneOf(
133+
{ bar: [Assert.equalTo('biz')] },
134+
{ bar: [Assert.equalTo('baz')] },
135+
{ bar: [Assert.equalTo('qux')] }
136+
).validate({ bar: 'qux' });
137+
});
138+
});
139+
140+
it('should pass if a constraint set contains an extra assert', ({ assert }) => {
141+
assert.doesNotThrow(() => {
142+
Assert.oneOf(
143+
{
144+
bar: [Assert.equalTo('biz')],
145+
baz: [Assert.oneOf({ qux: [Assert.equalTo('corge')] }, { qux: [Assert.equalTo('grault')] })]
146+
},
147+
{ bar: [Assert.equalTo('baz')] }
148+
).validate({ bar: 'biz', baz: { qux: 'corge' } });
149+
});
150+
});
151+
});

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)