To start using Altheia, require the package this way:
// TS
import alt from 'altheia-async-data-validator';
// js
const alt = require('altheia-async-data-validator').default
This documentation presents all available methods, but you can also refer to the Typescript definitions in your IDE.
Run the validation of the schema. You can
await
or pass a callback.
const errors = await alt({
login: alt.string().min(1),
}).validate({
login: 'foobar',
});
//=> "false" if no error
//=> "ValidatorErrorFormatted[]" if any errors
Set the body to be validated.
const hasError = await alt(...).body({
login: 'foobar'
}).validate();
Once a Validator has been validated, it carry on the results. You can clone it to clean the class and validate another body. It's light, it simply passes the schema reference without copying the results.
const schema = alt({
login: alt.string(),
});
const clone1 = schema.clone();
await clone1.body({ login: 'foo' }).validate();
const clone2 = schema.clone();
await clone2.body({ login: 1 }).validate();
By default, Altheia disallow unknown keys in the schema and does not require what you defined as mandatory. You can change these values to be more or less strict.
alt({
login: alt.string(),
}).options({
required: false, // :true, to force all fields to be required
unknown: false, // :true, to allow unknown fields
});
Because a single value validation cannot share any context with one another -- because everything is async -- confirmation is being done after in the global schema validation.
alt({
password: alt.string().min(6),
repeat: alt.string(),
})
.confirm('password', 'repeat')
.validate();
Add or change a lang entry.
alt.lang('string.min', () => `not good`);
Add a plugin to your Altheia instance
alt.use({
messages: { ... }
Class: class foobar extends alt.Base {}
});
All types inherit these methods.
Force an input to be different than
null
/undefined
alt.string().required();
Execute whatever you want, can be sync/async. The name parameter is there to identify this test if you want to add a
lang()
// Basic
alt.string().custom('my', (test) => {
return test === 'foobar';
});
alt.lang('string.custom.my', () => 'my custom test failed');
// With more complex validation
alt.string().custom('fooBar', (test) => {
const start = test.startsWith('foo');
if (!start) {
return {
valid: start,
error: 'wrongStart',
};
}
const end = test.endsWith('bar');
return {
valid: end,
error: !end ? 'wrongEnd' : false,
};
});
alt.lang('string.custom.fooBar', (name, args, result: { error: string }) => {
if (result.error === 'wrongStart')
return 'This string should start with "foo"';
if (result.error === 'wrongEnd') return 'This string should end with "bar"';
});
Alternatives are great to adapt the validation with some conditions. All functions are required to return an instance of a validator, but you can switch type between tests
// Same type
alt.string().if({
test: (test) => test.uppercase(),
then: (test) => test.min(10).max(50),
otherwise: (test) => test.email(),
});
// Type mixing
alt.any().if({
test: (test) => test.string(),
then: (test) => test.uppercase(),
otherwise: () => alt.number().min(10),
});
If you want to, you can validate only one input without the whole schema. You can await or pass callback
const hasError = await alt.string().validate(1);
//=> :false if no error
//=> :ValidatorTestResult if not
Any plugins is loaded by default since v3.0.0
Any inherits global methods and that's it. It allows chaining without knowing the type.
alt.any().required().custom();
Force a string to be not empty
""
, wether this validator is required or not. Altheia does make a difference betweennull/undefined
and""
.
alt.string().noEmpty().validate('');
Force a string to have a length of at least the value passed.
alt.string().min(1);
Force a string to have length of equal or less to the value passed.
alt.string().max(5);
Force a string to match the regex passed.
alt.string().pattern(/^[a-z]$/);
Force a string to exact match one of the values passed in the set.
alt.string().in('foo', 'bar');
Force a string to match none of the values passed in the set.
alt.string().not('bar', 'foo');
Force a string to be a valid email (contain an @).
alt.string().email();
Force a string to be entirely in lowercase.
alt.string().lowercase();
Force a string to be entirely in uppercase.
alt.string().uppercase();
Try to cast value to a number. This will not modify the original value.
alt.number().cast().validate('1');
Force a number to be equal or more to the value passed.
alt.number().min(5);
Force a number to be equal or less to the value passed.
alt.number().max(10);
Force a number to be an integer.
alt.number().integer();
Force a number to be unsigned.
alt.number().unsigned();
Force a number to be greater than 0.
alt.number().positive();
Force a number to be lesser than 0.
alt.number().negative();
Force a number to be equal to one of the values passed in the set.
alt.number().in(67, 35);
Force a number to be different to all the values passed in the set.
alt.number().not(42, 157);
Force an object to have only the keys passed in the set
Accept an optionnal second param:
{ oneErrorPerKey: boolean }
=>true
will return 1 error per invalid key.
// will return a single error even if multiple not matching
alt.object().in('foo', 'bar');
// will return one error per key not matching
alt.object().in(['foo', 'bar'], { oneErrorPerKey: true });
Force an object to match none of the keys passed in the set
alt.object().not('foo', 'bar');
Check an object with the passed schema. It will help you check nested object without effort. Because schema need to be instance of Altheia, you can do whatever you want without restriction.
Accept an optional second param:
returnErrors: boolean
=>false
will not display nested errors.
alt.object().schema(
Alt({
foo: alt.string(),
bar: alt.number(),
}).options({ required: true }),
{ returnErrors: false }
);
Force any keys, to be the only one present in the object (exclusive relationships)
Accept an optional first param:
- If the first argument is
true
, it will return an error if none match, otherwisefalse
(default) will not throw an error if none match.
// 'a', 'b', 'c', 'd'
// - none of them are required
alt.object().oneOf('a', 'b', 'c', 'd');
// 'a', 'b'
// - one of them is required
alt.object().oneOf(true, 'a', 'b');
Force all keys to be mutually required. If one is presents, all are required. Pass if none are present.
alt.object().allOf('a', 'b', 'c');
Force one or more keys to be present in the object.
alt.object().anyOf('a', 'b', 'c');
Force an array to contain at least a number of items equal to the value passed.
alt.array().min(5);
Force an array to contain at most a number of items equal to the value passed.
alt.array().max(10);
Force an array to have only the values passed in the set.
alt.array().in('foo', 'bar');
Force an array to have none of the values passed in the set.
alt.array().not('foo', 'bar');
Force an array to only have each value once. Use javascript
Set
, not shallow check.
alt.array().unique();
Force all array's items to match at least one of the template
alt.array().oneOf(alt.string(), alt.number());
Try to cast value to a boolean. Use javascript
Boolean(value)
.
alt.boolean().cast().validate('true');
alt.boolean().cast().validate('false');
Force a boolean to equal
true
.
alt.boolean().true();
Force a boolean to equal
false
.
alt.boolean().false();
Force a date to be a valid ISO-8601 date.
alt.date().iso();
Force a date to be a at least or bigger than the value passed.
alt.date().min(new Date('2017-08-01'));
Force a date to be less or equal than the value passed.
alt.date().max(new Date('2017-08-01'));
Force the value to be a valid url (RFC).
alt.internet().url();
Force the value to be a valid hostname (RFC).
alt.internet().hostname();
Force the value to be a valid hex (a-f0-9).
alt.internet().hex();
Force the value to be a valid credit card. Use Luhn's algorithm.
alt.internet().creditCard();
Force the value to be a valid uuid version 4.
alt.internet().uuidv4();
Force the value to be a valid ipv4 or ipv6.
alt.internet().ip();
Force the value to be a valid ipv4.
alt.internet().ipv4();
Force the value to be a valid ipv6.
alt.internet().ipv6();
There is no method right now, it will only check if the value is a valid function.
alt.function();