Skip to content

Commit

Permalink
Merge pull request #309 from Jasery/master
Browse files Browse the repository at this point in the history
fix: catch the custom validate function
  • Loading branch information
yiminghe committed Apr 24, 2022
2 parents 68e13b0 + abe3d8d commit d664fb8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
18 changes: 18 additions & 0 deletions __tests__/validator.spec.ts
Expand Up @@ -470,4 +470,22 @@ describe('validator', () => {
});
});
});

it('custom validate function throw error', done => {
new Schema({
v: [
{
validator(rule, value, callback) {
throw new Error('something wrong');
},
},
],
})
.validate({ v: '' })
.catch(({ errors }) => {
expect(errors.length).toBe(1);
expect(errors[0].message).toBe('something wrong');
done();
});
});
});
6 changes: 5 additions & 1 deletion src/index.ts
Expand Up @@ -283,7 +283,11 @@ class Schema {
if (rule.asyncValidator) {
res = rule.asyncValidator(rule, data.value, cb, data.source, options);
} else if (rule.validator) {
res = rule.validator(rule, data.value, cb, data.source, options);
try {
res = rule.validator(rule, data.value, cb, data.source, options);
} catch (error) {
cb(error.message);
}
if (res === true) {
cb();
} else if (res === false) {
Expand Down

0 comments on commit d664fb8

Please sign in to comment.