A simple and extendible object validator
npm install anubis-inspectA simple and extendible object validator
Use the package manager npm to install anubis-inspect.
``bash`
npm install anubis-inspect
`javascript
import { BaseValidator, StringField } from 'anubis-inspect';
const loginRules = {
username: new StringField("Username").max(20),
password: new StringField("Password")
}
class LoginValidator extends BaseValidator {
constructor() {
super();
super.init(loginRules);
}
}
const signUpRules = {
name: {
first: new StringField("First name"),
last: new StringField("Last name", false)
},
email: new StringField("email")
.test(async(email) => {
// simulating an API call
const isValid = await new Promise((resolve) => {
setTimeout(resolve, 1000, true);
})
// If email is valid nothing happens
// if it is invalid, the second element in the array is used as error message
return [isValid, "Invalid email"];
})
}
// SignUpValidaor will inherit the rules defined in LoginValidator
class SignUpValidator extends LoginValidator {
constructor() {
super();
super.init(signUpRules);
}
}
(async() => {
// Only the synchronous tests run
console.log(new SignUpValidator().validate({}))
// Both synchronous and asynchronous tests run
console.log(await new SignUpValidator().asyncValidate(
{
name: { first: 'First name' },
username: 'Username',
password: 'Password',
email: 'email@gmail.com'
}
))
})()
// Use with express middlewares
const app = express();
app.get("/sign-up", new SignUpValidator().middleware(), (req, res, next) => {
// API logic
})
`Things to keep in mind
A type-validator by default only checks for the presence and type of the value, to make the value optional or fit in a certain range, you must call the appropriate method, eg. new StringField('email') only makes sure that the value is not null/undefined and is a string, whereas new StringField('email', false) makes the email optional i.e allows either null/undefined or a string and new StringField('email').min(10) makes sure the email is at leats 10 characters long, every such method has a default error message to return if the value isn't as expected but you can pass your own messages too
The 'test' method allows you to add your own custom tests in form of functions, take the value, run tests (async tests too) and return an array in [isValid, errorMessage] format, the first item in the returned must be a boolean indicating if the value passes the test and the second is the error-message to be used in case the value failed the test
javascript
const rules = {
name: new StringField("Name").test((name) => {
return [name === "anubis", "Name must be anubis"]
})
}
`
2) async vanilla - an async function that takes the value of the field as the only parameter, example below
`javascript
const rules = {
name: new StringField("Name").test(async (name) => {
// simulating an API call
const isValid = await new Promise((resolve) => {
setTimeout(resolve, 1000, true);
})
return [isValid, "Invalid name"]
})
}
`
3) vanilla with dependencies - an function that takes the value of the field and other values that it depends on, the format is .test(testFunction, ["field"]), the first parameter is the test function and the second is an array of dependencies from the object being validated, if the dependency is a nested field just use the dot notation in the path like 'field1.field2', note that dependency values will be passed to your function in the same order you specified
`javascript
const rules = {
weight: new NumberField("Weight"),
unit: new StringField("Unit").test((unit, [weight]) => {
let isValid = false;
let message = "Invalid unit";
if (weight && !unit) {
message = "Unit for given weight is required";
} else if (unit && !weight) {
message = "Unit can only be given with weight";
} else {
isValid = true;
}
return [isValid, message];
}, ["weight"])
}
`
3) async with dependencies - a dependent test, but asynchronous
`javascript
const rules = {
weight: new NumberField("Weight"),
unit: new StringField("Unit").test(async (unit, [weight]) => {
// simulating an API call
const isUnitValid = await new Promise((resolve) => {
setTimeout(resolve, 1000, true, 1000);
})
return [isUnitValid, "Invalid unit"];
}, ["weight"])
}
``- ### instance methods
- requiredValueMessage(message) -> error message to return if the value is not provided
- invalidTypeMessage(message) -> error message to return if the value is not a string,
- min(min-range, [message]) -> the min number of characters
- max(max-range, [message]) -> the max number of characters
- match(regex, [message]) -> makes the value match the pattern
- test((value) => {}) -> passes the value through this function to check it's validity
- ### instance methods
- requiredValueMessage(message) -> error message to return if the value is not provided
- invalidTypeMessage(message) -> error message to return if the value is not a number
- min(minValue, [message]) -> the min value(inclusive)
- max(maxValue, [message]) -> the max value(inclusive)
- test((value) => {}, [message]) -> passes the value through this function to check it's validity
- ### instance methods
- requiredValueMessage(message) -> error message to return if the value is not provided
- invalidTypeMessage(message) -> error message to return if the value is not an integer
- min(minValue, [message]) -> the min value(inclusive)
- max(maxValue, [message]) -> the max value(inclusive)
- test((value) => {}, [message]) -> passes the value through this function to check it's validity
- ### instance methods
- requiredValueMessage(message) -> error message to return if the value is not provided
- invalidTypeMessage(message) -> error message to return if the value is not a float,
- min(minValue, [message]) -> the min value(inclusive)
- max(maxValue, [message]) -> the max value(inclusive)
- test((value) => {}, [message]) -> passes the value through this function to check it's validity
- ### instance methods
- requiredValueMessage(message) -> error message to return if the value is not provided
- invalidTypeMessage(message) -> error message to return if the value is not a float
- min(minValue, [message]) -> the min value(inclusive)
- max(maxValue, [message]) -> the max value(inclusive)
- test((value) => {}, [message]) -> passes the value through this function to check it's validity
- ### instance methods
- requiredValueMessage(message) -> error message to return if the value is not provided
- invalidTypeMessage(message) -> error message to return if the value is not an array
- min(minValue, [message]) -> the min array length(inclusive)
- max(maxValue, [message]) -> the max array length(inclusive)
- values(type-validator, [message]) -> validates the array items with the type-validator passed
- notNested() -> rejects nested arrays
- test((value) => {}, [message]) -> passes the value through this function to check it's validity
- ### instance methods
- requiredValueMessage(message) -> error message to return if the value is not provided
- invalidTypeMessage(message) -> error message to return if the value is not an array
- min(minValue, [message]) -> the min number of keys(inclusive)
- max(maxValue, [message]) -> the max number of keys(inclusive)
- values(type-validator, [message]) -> validates the object values with the type-validator passed, doesn't validate keys, they'll always be strings
- notNested() -> rejects nested objects
- test((value) => {}, [message]) -> passes the value through this function to check it's validity
- ### instance methods
- invalidTypeMessage(message) -> error message to return if the value is not null
- ### instance methods
- invalidTypeMessage(message) -> error message to return if the value is not undefined