Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use a schema as when condition #445

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions src/Condition.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ function callOrConcat(schema) {
return base => base.concat(schema);
}

function makeIsFn(refs, predicate) {
return refs.length < 2 ? predicate : (...values) => values.every(predicate);
}

class Conditional {
constructor(refs, options) {
let { is, then, otherwise } = options;
Expand All @@ -26,10 +30,15 @@ class Conditional {
'either `then:` or `otherwise:` is required for `when()` conditions',
);

let isFn =
typeof is === 'function'
? is
: (...values) => values.every(value => value === is);
let isFn;

if (typeof is === 'function') {
isFn = is;
} else if (isSchema(is)) {
isFn = makeIsFn(this.refs, value => is.isValidSync(value));
} else {
isFn = makeIsFn(this.refs, value => value === is);
}

this.fn = function(...values) {
let currentSchema = values.pop();
Expand Down
16 changes: 16 additions & 0 deletions test/mixed.js
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,22 @@ describe('Mixed Types ', () => {
await inst.validate(-1).should.be.fulfilled();
});

it('should handle conditionals with schema as condition', async function() {
let inst = object({
flag: mixed(),
prop: number().when('flag', {
is: bool(),
then: number().min(5),
}),
});

await inst.validate({ flag: 'hello', prop: 4 }).should.be.fulfilled();

await inst
.validate({ flag: true, prop: 4 })
.should.be.rejectedWith(ValidationError, /must be greater than/);
});

it('should use label in error message', async function() {
let label = 'Label';
let inst = object({
Expand Down