policeman
Lightweight yet powerful schema validator
API Docs | Examples
- Validate objects based on provided schema
- Inspired by mappet
Installation (npm)
npm i -S policeman
Examples
import policeman, { isRequired, isEmail, isMatching, combineValidators } from "policeman";
const requiredValidator = isRequired(() => "is required");
const emailValidator = isEmail(() => "is invalid email");
const phoneNumberValidator = isMatching(/\d{3}-?\d{3}-?\d{3}/, () => "is invalid phone");
const skipIfGift: Filter = (value: any, source: User) => source.gift === true;
const schema = [
["email", "email", [requiredValidator, emailValidator]],
["phone", "phone", combineValidators(requiredValidator, phoneNumberValidator)],
["name", "name", requiredValidator],
["giftCode", "giftCode", requiredValidator, skipIfGift],
];
const validator = policeman(schema);
validator({ gift: false, email: "invalid@example", phone: "777-666-55" });
See tests for more examples.
Built-in validators
All built-in validators are curried.
isRequired(() => message, value)
Validates presence. Fails on null
, empty string or undefined
.
isMinLength(min, () => message, value)
Passed value
must be a string longer or with length equal to min
.
isMaxLength(max, () => message, value)
Passed value
must be a string shorther or with length equal to max
.
isEqualLength(equal, () => message, value)
Passed value
must be a string shorther or with length equal to max
.
isEmail(() => message, value)
Passed value
must be a valid email. It's a simple check, if you need more complex solution use
isMatching
or isPassing
.
isMatching(regexp, () => message, value)
Passed value
must pass regexp
.
isPassing(predicate, () => message, value)
Passed predicate
answers on "Is value
valid?". When predicate
returns true
validator passes,
when predicate
returns false
error message is returned.
It makes policeman
compatible with all available validators i.e. validator.
import validator from "validator";
import { isPassing } from "policeman";
const isCreditCard = isPassing(validator.isCreditCard, () => "is invalid credit card");
const isUUID4 = isPassing(value => validator.isUUID(value, 4), () => "is invalid UUID v4");
const isFTP = isPassing(value => validator.isURL(value, { protocols: ["ftp"] }, () => "is invalid FTP address");
See tests for more examples.