What is checkit?
Checkit is a validation library for JavaScript that allows you to define and enforce rules for your data. It is particularly useful for validating user input in web applications.
What are checkit's main functionalities?
Basic Validation
This feature allows you to define basic validation rules for your data. In this example, the 'name' field must be present and contain only alphabetic characters, while the 'age' field must be present, an integer, and at least 18.
const Checkit = require('checkit');
const rules = new Checkit({
name: ['required', 'alpha'],
age: ['required', 'integer', 'min:18']
});
rules.run({ name: 'John', age: 25 })
.then(validated => console.log('Validated:', validated))
.catch(err => console.error('Validation failed:', err));
Custom Validation
This feature allows you to define custom validation rules. In this example, a custom rule is added to Checkit's Validator prototype, which checks if the value of 'customField' is 'customValue'.
const Checkit = require('checkit');
Checkit.Validator.prototype.customRule = function(val) {
if (val !== 'customValue') {
throw new Error('Value must be customValue');
}
};
const rules = new Checkit({
customField: ['customRule']
});
rules.run({ customField: 'customValue' })
.then(validated => console.log('Validated:', validated))
.catch(err => console.error('Validation failed:', err));
Asynchronous Validation
This feature allows you to define asynchronous validation rules. In this example, an asynchronous rule is added to Checkit's Validator prototype, which checks if the value of 'asyncField' is 'asyncValue' after a delay.
const Checkit = require('checkit');
Checkit.Validator.prototype.asyncRule = function(val) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (val === 'asyncValue') {
resolve();
} else {
reject(new Error('Value must be asyncValue'));
}
}, 1000);
});
};
const rules = new Checkit({
asyncField: ['asyncRule']
});
rules.run({ asyncField: 'asyncValue' })
.then(validated => console.log('Validated:', validated))
.catch(err => console.error('Validation failed:', err));
Other packages similar to checkit
joi
Joi is a powerful schema description language and data validator for JavaScript. It allows you to create blueprints or schemas for JavaScript objects to ensure validation of key information. Compared to Checkit, Joi offers a more extensive set of built-in validation rules and better integration with modern JavaScript frameworks.
validator
Validator is a library of string validators and sanitizers. It is highly performant and provides a wide range of validation and sanitization functions. Unlike Checkit, which is more focused on object validation, Validator is specialized in string validation.
yup
Yup is a JavaScript schema builder for value parsing and validation. It is similar to Joi but is more lightweight and has a more modern API. Yup is often used in React applications for form validation. Compared to Checkit, Yup offers better integration with modern front-end frameworks and a more intuitive API.
CheckIt
Simple validations for node.js and the browser
The CheckIt library aims to be a lightweight, flexible, validation library,
with no dependence on the DOM, targeting both Node.js and the browser.
CheckIt depends on underscore.js, the underscore.function.predicates.js
of underscore-contrib and (optionally)
when.js for using the library asynchronously with promises. If you
wish to use when, but would rather use browser globals than a package manager, a shimmed version of
when is included in the /lib
directory for your convenience.
Getting Started
Creating a CheckIt object starts with specifying a target to be validated, as well as an optional
options object to help setup the validation settings such as language and async.
var validator = CheckIt(target, options);
Validating an object
The run
method passes through to runAsync
or runSync
depending on whether the async flag is set globally or in the
options passed to the CheckIt
object.
validator.run(validations);
Methods:
setLabels(labels)
Applies the labels for the current validation values, so error messages aren't weird looking and such.
applyToAll(rules)
Takes a rule, or array of rules to be applied against each item in the validation target.
run([rules])
The rules are optional, particularly
Validation options:
If no language is specified, then the value of CheckIt.defaultLanguage
will
be used (defaults to "en").
Errors:
The CheckIt.Error
object is used to handle all errors. If a validation is run synchronously,
the validation will return false and this value will be set to the .validationError
property
on the currently validating instance. If the validation is run asynchronously, this error will
be passed in rejecting the promise.
CheckIt.Error Methods
get(key)
Gets the array of validation error messages for a particular key off the validation object.
first(key)
Gets the first of validation error messages for a particular key.
toJSON([all])
Turns the validation errors into a hash. If the optional all is set to true, then it
returns an array of messages rather than the first validation message for each error key.
toString()
A string saying how many errors have been triggered total in the current validation.
Example:
var example = {
'user' : 'Joe User',
'email' : 'joe@example.com',
'password' : '123',
'password_confirm' : '456'
};
Example 1: Simple Validation
CheckIt(example).run({
'user' : ['required', 'alphaDash', 'maxLength:255'],
'email' : ['required', 'validEmail'],
'password' : ['required']
'password_confirm': ['matchesField:password']
}).then(function(validator) {
}, function(err) {
});