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

Other validations #14

Merged
merged 2 commits into from
Jul 19, 2018
Merged
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
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,22 @@ if (result.valid) doThing(result.data);
else logger.error(...result.errors);
```

### Validator.withOptions
Add additional validations to the generated schema.
While most of these validations are not representable at compile time
with typescript (`minLength` of a `string` for instance), it can be helpful
to have the additional validations when validating runtime types.

| Param | Description |
| --- | --- |
| opts | JSON schema specific options (for instance: `{ maxLength: 2, minLength: 0 }`) |
###### Example:
```typescript
const validator = v.string().withOptions({ minLength: 1 });
validator.isValid(''); // false
validator.isValid('hi'); // true
```

### ValidType
Returns the encapsulated type of a `Validator` type.
###### Example:
Expand Down
49 changes: 47 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
import { Schema, SchemaMetaData } from 'type-level-schema/schema';
import { objectKeys, Nominal, AnyFunc, AllRequired, Optional, Unknown, PlainObject } from 'simplytyped';
import { objectKeys, Nominal, AnyFunc, AllRequired, Optional, Unknown, PlainObject, Omit } from 'simplytyped';
import * as Ajv from 'ajv';

// Schema definitions
import { Schema, SchemaMetaData } from 'type-level-schema/schema';
import { StringSchema } from 'type-level-schema/defs/string';
import { NumberSchema } from 'type-level-schema/defs/number';
import { BooleanSchema } from 'type-level-schema/defs/boolean';
import { ArraySchema } from 'type-level-schema/defs/array';
import { ObjectSchema } from 'type-level-schema/defs/object';

/**
* no-doc - Gets the full schema definition for a given type.
*/
export type TypeToSchema<T> =
T extends string ? StringSchema :
T extends number ? NumberSchema :
T extends boolean ? BooleanSchema :
T extends any[] ? ArraySchema :
T extends object ? ObjectSchema :
never;

/**
* no-doc - Gets the optional parts of the schema definition for a given type.
*/
export type TypeToSchemaOptions<T> = Omit<TypeToSchema<T>, 'type'>;

/**
* no-doc - Generates an object type from `[string, Validator]` pairs
* @param O a Validator record
Expand Down Expand Up @@ -182,6 +205,28 @@ export class Validator<T> {
return this;
}

/**
* Add additional validations to the generated schema.
* While most of these validations are not representable at compile time
* with typescript (`minLength` of a `string` for instance), it can be helpful
* to have the additional validations when validating runtime types.
* @param opts JSON schema specific options (for instance: `{ maxLength: 2, minLength: 0 }`)
*
* @example
* ```typescript
* const validator = v.string().withOptions({ minLength: 1 });
* validator.isValid(''); // false
* validator.isValid('hi'); // true
* ```
*/
withOptions(opts: TypeToSchemaOptions<T>): this {
this.schema = {
...this.schema,
...opts as any,
};
return this;
}

/**
* Creates a new validator that is true whenever the data matches `this` _or_ `v`.
* @param other Another validator instance whose type will form a union with `this` encapsulated type.
Expand Down
11 changes: 11 additions & 0 deletions tests/unit/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,14 @@ test('Can validate a deep array', () => {
fail();
}
});

test('Can add JSON Schema options', () => {
const x: any = [ 'yellow!' ];

const validator = v.array(v.any())
.withOptions({ minItems: 2 });

// expect to fail because we have fewer than 2 items
if (validator.isValid(x)) fail();
else pass();
});
10 changes: 10 additions & 0 deletions tests/unit/string.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,13 @@ test('String is not in enum', () => {
if (validator.isValid(x)) fail();
else pass();
});

test('Can add JSON Schema options', () => {
const x: any = '';

const validator = v.string()
.withOptions({ minLength: 1 });

if (validator.isValid(x)) fail();
else pass();
});