pp-validate
v2.0.0
Published
Function for validate data object from rules.
Readme
pp-validate
pp-validate is a small function for validating a data object against a set
of rules. As of v2, its rule set is derived automatically from
pp-is: every isXxx predicate
pp-is exposes (isEmail, isUUID, isIPv4, isAlpha, isHexColor, ...)
becomes a validation rule for free, so pp-validate grows every time pp-is
does.
Getting Started
In the browser, include pp-validate with:
<script src="https://cdn.jsdelivr.net/npm/pp-validate@latest/dist/pp-validate.iife.js"></script>This bundle includes its pp-is dependency inline, so no other script tag
is needed. It exposes a global ppValidate function.
Or install it for Node.js / a bundler:
npm i pp-validate --saveQuick start
validate() is async (rules may be asynchronous, e.g. checking a value
against a server) and returns { valid, errors }:
var validate = require('pp-validate'); // or: import validate from 'pp-validate'
var data = {
name : "Jhon Smith",
age : 30,
email : "[email protected]",
website : "https://jsmith.com",
pass : "12345678",
repeatpass : "12345678",
something : "Hello World"
};
var rules = {
name : { minlength: 6 },
age : { number: true, range: [18, 65] },
email : { email: true, minlength: 10 },
website : { url: true },
pass : { minlength: 8 },
repeatpass : { equalTo: "pass" },
something : { presence: true }
};
validate(data, rules).then(function (result) {
if (result.valid) {
console.log("data validated: successful");
} else {
console.log(result.errors); // { field: { rule: "human readable message" } }
}
});If every rule you use is synchronous, validateSync(data, rules) is
available too and returns the result directly (no Promise):
var result = validate.validateSync(data, rules);Rules
Derived automatically from pp-is
Any single-argument isXxx predicate pp-is exports becomes a boolean rule
named after it (isUUID -> uuid, isIPv4 -> ipv4, isEmail -> email,
...). This list grows with pp-is without any change to pp-validate. As of
this release it includes, among others:
string, number, boolean, array, object, date, email, url,
regexp, integer, positive, negative, alpha, alphanumeric,
numericstring, lowercase, uppercase, hexcolor, json, uuid,
ipv4, iterable, truthy, falsy, callable, asyncfunction,
promise, frozen, sealed, empty, blank, nil.
validate({ id: "a-uuid-goes-here" }, { id: { uuid: true } });
validate({ ip: "192.168.0.1" }, { ip: { ipv4: true } });Built-in parametric rules
- range: [min, max] — number is within an inclusive range.
- min / max: number — number is
>=/<=the given limit. - minlength / maxlength: number — string length is
>=/<=the given limit. - regex / no_regex: RegExp — value does / does not match the pattern.
- equalTo: "otherField" — value equals another field's value.
- required: true — value is not
undefined,null,""or[]. - presence: true — the key must exist in the data object (independent of its value).
Custom rules
var { extend } = require('pp-validate');
extend('creditCard', function (value) { return luhnCheck(value); });
extend('usernameAvailable', async function (value) {
return !(await api.usernameTaken(value));
});
// now usable as { creditCard: true } / { usernameAvailable: true } in any rules objectForm validation
pp-validate/form binds a rules object directly to a real <form>
element — framework-agnostic, no dependency beyond the DOM itself:
import { bindForm } from 'pp-validate/form';
var controller = bindForm(document.querySelector('#signup'), {
rules: {
email: { email: true },
pass: { minlength: 8 }
},
on: 'blur', // 'blur' | 'input' | null
onError(field, errors) { field.el.classList.add('invalid'); },
onValid(field) { field.el.classList.remove('invalid'); }
});
controller.el.addEventListener('submit', async function (event) {
event.preventDefault();
var result = await controller.validate();
if (result.valid) submitForm();
});Or drop-in via <script>:
<script src="https://cdn.jsdelivr.net/npm/pp-validate@latest/dist/pp-validate.form.iife.js"></script>
<script>
ppValidateForm.bindForm(document.querySelector('#signup'), { rules: { /* ... */ } });
</script>Migrating from v1
validate()is now async — useawait/.then(), or callvalidate.validateSync(...)when every rule is synchronous.- The result shape changed from
{ valid, error }(booleans) to{ valid, errors }(human-readable messages per failing rule). - The old string syntax (
"minlength:6|maxlength:50") still works unchanged, including themailalias foremail. New code should prefer plain rule objects ({ minlength: 6, maxlength: 50 }), which avoid the string-parsing edge cases of the old format.
