- API Reference
All types created by a validator get the validators options as default options. The options can get overwritten for every type.
options
:
locale (string)
: The anguage locale. Defaulten
requiredAsDefault (boolean)
: Sets all parameters of a schema as required if not specified otherwise. Defaulttrue
.throwValidationErrors (boolean)
: Throw an error if validation fails. Defaulttrue
.parseToType (boolean)
: Parse input data to type (e.g. 'true' -> true, '1.2' -> 1.2). Defaulttrue
,emptyStrings (boolean)
: Allow empty strings. Defaultfalse
,trimStrings (boolean)
: Trim strings. Defaulttrue
,emptyArrays (boolean)
: Allow empty arrays. Defaultfalse
,emptyObjects (boolean)
: Allow empty objects. Defaultfalse
,unknownObjectKeys (boolean)
: Allow keys that are not defined by the schema. Defaultfalse
,parseDates (boolean)
: Parse date string to Date objects. Defaulttrue
,utc (boolean)
: Use UTC to parse dates. Defaulttrue
,nullAsUndefined (boolean)
: Treat null values as undefined. Defaultfalse
. AngularValidator(Default:true
)
Add a custom language pack. Check the locales folder for the available keys.
validator.addLocale('custom', {
wrong_type: 'Beep'
// ...
});
Set the language.
validator.setLocale('de');
Add a custom type to reuse it later.
const address = validator.Object({
street: validator.String(),
postal: validator.Integer(),
city: validator.String()
});
validator.addType('address', address);
Use a custom type.
validator.Custom('address').validate(value);
List all custom types.
console.log(validator.listCustomTypes());
// [ 'address: OBJECT' ]
Validate a schema with the validator to return a ValidationError
object.
const validator = Validator();
validator.validate(validator.String(), undefined);
// ValidationError({
// message: 'Invalid input parameters and/or values.',
// code: 'validation_error',
// type: 'validator',
// details: 'Required but is undefined'
// })
Validate a schema with the validator to return a ValidationError
object.
const validator = Validator();
validator.validateSync(validator.String(), undefined);
// ValidationError({
// message: 'Invalid input parameters and/or values.',
// code: 'validation_error',
// type: 'validator',
// details: 'Required but is undefined'
// })
The base type Any
is inherited by all other types, therefore the following functions are availabe for all types. An optional options object can be passed to the constructor to overwrite the validators default options.
Asynchronous validation of a schema.
const schema = validator.Any();
schema.validate('test').then(value => {
// test
});
Synchronous validation of a schema.
const schema = validator.Any();
schema.validateSync('test');
// test
Marks a key as required which will not allow undefined as value
const schema = validator
.Any()
.required()
.validate(undefined);
// throws
Marks a key as optional which will allow undefined as value
const schema = validator
.Any()
.optional()
.validate(undefined);
// undefined
Creates a copy of the schema.
const requiredSchema = validator
.Any()
.example('test')
.required();
const optionalSchema = schema.clone().optional();
Sets a description for the type. Useful for automated documentation generation.
const schema = validator.Any().example('Any value is allowed.');
Provide an example for the key. Useful for automated documentation generation.
If no parameter is given, the schemas example is returned
const schema = validator.Any().example('test');
schema.example();
// test
Set a default value used if key is empty.
const schema = validator
.Any()
.default('test')
.validate(undefined);
// test
Parse value to schema type.
const schema = validator
.Boolean()
.parse(true)
.validate('true');
// true
Only allow the given values.
const schema = validator
.Any()
.only('test', 'hello')
.validate('wrong');
// throws
Disallow the given values.
const schema = validator
.Any()
.not('test', 'hello')
.validate('test');
// throws
Allow specific values.
const schema = validator
.Any()
.allow(null, 'test')
.validate(null);
// null
Use a custom function for validation.
validate() supports normal functions and async functions
validateSync() only supports normal functions
If the function has a return value, it will overwrite the given value
The function can throw a literal or an error.
const schema = validator.Any()
.func((value) => {
if (value === 'wrong') {
throw 'So wrong.';
} else {
return 'test';
});
schema.validate('wrong');
// throws
schema.validate('hello');
// test
Returns an object representation of the schema.
const schema = validator.Number().integer(true);
schema.toObject();
// { type: 'number', required: true, integer: true }
schema.toObject({ type: 'raml' });
// { type: 'integer', required: true }
Set a minimum length of the array.
const schema = validator
.Array()
.min(2)
.validate(['test']);
// throws
Set a minimum length of the array.
const schema = validator
.Array()
.max(1)
.validate(['test', 'hello']);
// throws
Set the exact length of the array.
const schema = validator
.Array()
.length(1)
.validate(['test']);
// ['test']
Allow array to be empty.
const schema = validator
.Array()
.empty(false)
.validate([]);
// throws
Require unique array items.
const schema = validator
.Array()
.unique(true)
.validate(['test', 'test']);
// throws
const schema = validator.Boolean().validate(false);
// false
The given value will get validated with moment. Default format is the ISO6801 standard 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'.
const schema = validator
.Date()
.format('YYYY-MM-DD')
.validate('2018');
// throws
Use UTC time.
const schema = validator
.Date()
.utc(true)
.validate('2018');
// UTC Date object
Set a minimum date.
const schema = validator
.Date()
.min('2018-01-01T00:00:00.000Z')
.validate('2017-01-01T00:00:00.000Z');
// throws
Set a maximum date.
const schema = validator
.Date()
.max('2018-01-01T00:00:00.000Z')
.validate('2017-01-01T00:00:00.000Z');
// Date object
Require integer values.
const schema = validator
.Number()
.integer()
.validate(2.2);
// throws
Set a minimum value.
const schema = validator
.Number()
.min(5)
.validate(2.2);
// throws
Set a maximum value.
const schema = validator
.Number()
.max(5)
.validate(2.2);
// 2.2
Require value to be less than given number.
const schema = validator
.Number()
.less(5)
.validate(2.2);
// 2.2.
Require value to be greater than given number.
const schema = validator
.Number()
.greater(5)
.validate(2.2);
// throws
Require value to be a positive number.
const schema = validator
.Number()
.positive()
.validate(0);
// throws
Require value to be a negative number.
const schema = validator
.Number()
.negative()
.validate(0);
// throws
Allow object to be empty.
const schema = validator
.Object()
.empty(true)
.validate({});
// {}
Allow unknown object keys.
const schema = validator
.Object({ name: validator.String() })
.unknown(false)
.validate({ name: 'Jane Doe', age: 26 });
// throws
Execute a custom function with the values of the given keys as parameters.
validate() supports async and sync functions
validateSync() only supports sync functions
const schema = validator
.Object({
name: validator.String(),
age: validator.Number()
})
.func(async (name, age) => {}, 'name', 'age')
.validate({ name: 'John Doe', age: 30 });
// { name: 'John Doe' }
Set a minimum number of object keys.
const schema = validator
.Object()
.min(2)
.validate({});
// throws
Set a maximum number of object keys.
const schema = validator
.Object({ name: validator.String() })
.max(2)
.validate({ name: 'John Doe' });
// { name: 'John Doe' }
Set the exact number of object keys.
const schema = validator
.Object({ name: validator.String() })
.length(1)
.validate({ name: 'John Doe' });
// { name: 'John Doe' }
a
must be greater than b
const schema = validator
.Object({
a: validator.Number(),
b: validator.Number()
})
.gt('a', 'b')
.validate({ a: 0, b: 2 });
// throws
a
must be greater than or equal b
const schema = validator
.Object({
a: validator.Number(),
b: validator.Number()
})
.gte('a', 'b')
.validate({ a: 2, b: 2 });
// { a: 2, b: 2}
a
must be less than b
const schema = validator
.Object({
a: validator.Number(),
b: validator.Number()
})
.lt('a', 'b')
.validate({ a: 0, b: 2 });
// { a: 0, b: 2}
a
must be less than or equal b
const schema = validator
.Object({
a: validator.Number(),
b: validator.Number()
})
.lte('a', 'b')
.validate({ a: 5, b: 2 });
// throws
a
must equal b
const schema = validator
.Object({
a: validator.Number(),
b: validator.Number()
})
.equals('a', 'b')
.validate({ a: 5, b: 2 });
// throws
a
must not equal b
const schema = validator
.Object({
a: validator.Number(),
b: validator.Number()
})
.notEquals('a', 'b')
.validate({ a: 2, b: 2 });
// throws
a
dependsOn b
const schema = validator
.Object({
a: validator.Number().optional(),
b: validator.Number().optional()
})
.dependsOn('a', 'b')
.validate({ a: 5 });
// throws
Only a
or b
must be set.
const schema = validator
.Object({
a: validator.Number().optional(),
b: validator.Number().optional()
})
.xor('a', 'b')
.validate({});
// throws
Only a
or b
can be set.
const schema = validator
.Object({
a: validator.Number().optional(),
b: validator.Number().optional()
})
.or('a', 'b')
.validate({ a: 2, b: 2 });
// throws
Set minimum length of the string.
const schema = validator
.String()
.min(10)
.validate('test');
// throws
Set maximum length of the string.
const schema = validator
.String()
.max(10)
.validate('test');
// test
Set exact length of the string.
const schema = validator
.String()
.length(4)
.validate('test');
// test
Allow string to be empty.
const schema = validator
.String()
.empty(false)
.validate('');
// throws
Trim string.
const schema = validator
.String()
.trim(true)
.validate(' string with whitespaces ');
// string with whitespaces
Value must match the regular expression.
const schema = validator.String().regex(/[A-Z]/, {
en: 'Only uppercase letters.',
de: 'Nur Großbuchstaben'
});
schema.validate('ABC');
// ABC
schema.validate('abc');
// Only uppercase letters.