diff --git a/jjv/jjv-tests.ts b/jjv/jjv-tests.ts new file mode 100644 index 000000000..d290fe9ab --- /dev/null +++ b/jjv/jjv-tests.ts @@ -0,0 +1,69 @@ +/// + +import jjv = require('jjv'); + +// create new JJV environment +var env = jjv(); +var errors: jjv.Errors; + +// Register a `user` schema +env.addSchema('user', { + type: 'object', + properties: { + firstname: { + type: 'string', + minLength: 2, + maxLength: 15, + }, + lastname: { + type: 'string', + minLength: 2, + maxLength: 25, + }, + gender: { + type: 'string', + enum: ['male', 'female'], + }, + email: { + type: 'string', + format: 'email', + }, + password: { + type: 'string', + minLength: 8, + }, + }, + required: ['firstname', 'lastname', 'email', 'password'], +}); + +// Perform validation against an incomplete user object (errors will be reported) +errors = env.validate('user', { firstname: 'John', lastname: 'Smith' }); + +errors = env.validate({ + type: 'object', + properties: { + x: { type: 'number' }, + y: { type: 'number' }, + }, + required: ['x', 'y'], +}, { x: 'a' }); + +if (errors.validation['x'].type === 'string') { + console.log('x is wrong type'); +} + +if (errors.validation['y'].required) { + console.log('y is required'); +} + +env.defaultOptions.checkRequired = false; + +env.validate('schemaName', {}, { checkRequired: false }); + +env.addType('date', (v: any) => !isNaN(Date.parse(v))); + +env.addFormat('hexadecimal', (v: any) => (/^[a-fA-F0-9]+$/).test(v)); + +env.addCheck('exactLength', (v: any, p: any) => v.length === p); + +env.addTypeCoercion('integer', (x: any) => parseInt(x, 10)); diff --git a/jjv/jjv.d.ts b/jjv/jjv.d.ts new file mode 100644 index 000000000..9dd9c6410 --- /dev/null +++ b/jjv/jjv.d.ts @@ -0,0 +1,42 @@ +// Type definitions for JJV v1.0.2 +// Project: https://github.com/acornejo/jjv +// Definitions by: Wim Looman +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "jjv" { + function jjv(): jjv.Env; + + module jjv { + interface Errors { + validation: { + [property: string]: { + required?: boolean; + type?: string; + } + }; + } + + interface Options { + checkRequired?: boolean; + useDefault?: boolean; + useCoerce?: boolean; + removeAdditional?: boolean; + } + + interface Env { + defaultOptions: Options; + + addSchema(name: string, schema: Object): void; + + addType(name: string, parse: (input: any) => any): void; + addFormat(name: string, parse: (input: any) => any): void; + addCheck(name: string, check: (input: any, comparator: any) => any): void; + addTypeCoercion(name: string, coerce: (input: any) => any): void; + + validate(name: string, object: any, options?: Options): Errors; + validate(schema: Object, object: any, options?: Options): Errors; + } + } + + export = jjv; +}