Releases: icebob/fastest-validator
Releases · icebob/fastest-validator
v0.6.11
v0.6.10
v0.6.9
v0.6.7
v0.6.6
v0.6.3
Browser support
From now the library is working in browsers as well. Thanks for incubus8!
Example in vanilla JS:
<script src="https://unpkg.com/fastest-validator"></script>
var v = new FastestValidator();
const schema = {
multi: [
{ type: "string", min: 3, max: 255 },
{ type: "boolean" }
]
};
console.log(v.validate({ multi: "John" }, schema));
// Returns: true
No dependencies
We removed all dependencies.
v0.5.0
Multiple validators
There is possible to define more validators for a field. In this case if one of all validators is success, the field will be valid.
let schema = {
cache: [
{ type: "string" },
{ type: "boolean" }
]
}
v.validate({ cache: true }, schema); // Valid
v.validate({ cache: "redis://" }, schema); // Valid
v.validate({ cache: 150 }, schema); // Fail
Custom validator
You can also create your custom validator.
let v = new Validator({
messages: {
// Register our new error message text
evenNumber: "The '{field}' field must be an even number! Actual: {actual}"
}
});
// Register a custom 'even' validator
v.add("even", value => {
if (value % 2 != 0)
return v.makeError("evenNumber", null, value);
return true;
});
const schema = {
name: { type: "string", min: 3, max: 255 },
age: { type: "even" }
};
console.log(v.validate({ name: "John", age: 20 }, schema));
// Returns: true
console.log(v.validate({ name: "John", age: 19 }, schema));
/* Returns an array with errors:
[{
type: 'evenNumber',
expected: null,
actual: 19,
field: 'age',
message: 'The \'age\' field must be an even number! Actual: 19'
}]
*/
Or you can use the custom
type with inline checker function:
let v = new Validator({
messages: {
// Register our new error message text
weightMin: "The weight must be larger than {expected}! Actual: {actual}"
}
});
const schema = {
name: { type: "string", min: 3, max: 255 },
weight: {
type: "custom",
minWeight: 10,
check(value, schema) {
return (value < schema.minWeight)
? this.makeError("weightMin", schema.minWeight, value)
: true;
}
}
};
console.log(v.validate({ name: "John", weight: 50 }, schema));
// Returns: true
console.log(v.validate({ name: "John", weight: 8 }, schema));
/* Returns an array with errors:
[{
type: 'weightMin',
expected: 10,
actual: 8,
field: 'weight',
message: 'The weight must be larger than 10! Actual: 8'
}]
*/