Skip to content

Commit

Permalink
Add parse options to is()
Browse files Browse the repository at this point in the history
  • Loading branch information
jonlambert committed Sep 18, 2023
1 parent 45c9892 commit 597af57
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 6 deletions.
5 changes: 3 additions & 2 deletions library/src/methods/is/is.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ describe('is', () => {
expect(is(object({ test: string() }), {})).toBe(false);
});

test('should skip pipelines', () => {
expect(is(string([minLength(1)]), '')).toBe(true);
test('should accept parsing options', () => {
expect(is(string([minLength(1)]), '', { skipPipe: true })).toBe(true);
expect(is(string([minLength(1)]), '', { skipPipe: false })).toBe(false);
});
});
8 changes: 5 additions & 3 deletions library/src/methods/is/is.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import type { BaseSchema, Input } from '../../types.ts';
import type { BaseSchema, Input, ParseInfo } from '../../types.ts';

/**
* Checks if the input matches the scheme. By using a type predicate, this
* function can be used as a type guard.
*
* @param schema The schema to be used.
* @param input The input to be tested.
* @param info The optional parse info.
*
* @returns Whether the input matches the scheme.
*/
export function is<TSchema extends BaseSchema>(
schema: TSchema,
input: unknown
input: unknown,
info?: ParseInfo
): input is Input<TSchema> {
return !schema._parse(input, { abortEarly: true, skipPipe: true }).issues;
return !schema._parse(input, { abortEarly: true, ...info }).issues;
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ if (result.success) {

Another way to validate data that can be useful in individual cases is to use a type guard. A type guard is an if-condition which, if `true`, sets the parsed data to the input type of a schema.

If a type guard is used, the issues of the validation cannot be accessed. Also, pipelines are skipped, transformations have no effect and unknown keys of an object are not removed. Therefore, this approach is not as safe and powerful as the two previous ways. Also, it can currently only be used with syncronous schemas.
If a type guard is used, the issues of the validation cannot be accessed. Also, transformations have no effect and unknown keys of an object are not removed. Therefore, this approach is not as safe and powerful as the two previous ways. Also, it can currently only be used with syncronous schemas.

```ts
import { email, is, string } from 'valibot'; // 0.55 kB
Expand Down

0 comments on commit 597af57

Please sign in to comment.