Simple validations for node and the browser.
A DOM-independent validation library for Node.js, io.js and the browser.
It supports both sync
var mainRules = Checkitrules;mainRulesrunobjthenconsole.log'The fields: ' + _keysvalidatedFieldsjoin', ' + ' were validated!';caughtCheckitError$"#errors"htmlerrmapreturn '<li>' key + ': ' + valfirstmessage + '</li>';join'';;
npm install checkit
Checkit constructor may be called with or without the
new keyword, taking a hash of fields/rules for these fields to be validated.
Used to specify the default language key for using a particular language file, currently en and es are supported.
Specifies labels for use in error messages for specific keys
Adds specific messages for individual errors
var checkit =firstName: 'required'lastName: 'required'email: 'required' 'email';var body =email: 'firstname.lastname@example.org'firstName: 'Tim'lastName: 'Griesser'githubUsername: 'tgriesser';checkitrunbodythenconsole.logvalidated;catchCheckitErrorconsole.logerrtoJSON;
var checkit =firstName: 'required'lastName: 'required'email: 'required' 'email';var body =email: 'email@example.com'firstName: 'Tim'lastName: 'Griesser'githubUsername: 'tgriesser';var err validated = checkitvalidateSyncbody// ...
Checkitcheck'email' email 'required' 'validEmail'catchconsole.logerrmessage;
// ES6...var err resp = CheckitcheckSync'email' email 'required' 'validEmail'if errelse// ...
|accepted||The value must be yes, on, or 1. This is useful for validating "Terms of Service" acceptance.|
|alpha||The value must be entirely alphabetic characters.|
|alphaDash||The value may have alpha-numeric characters, as well as dashes and underscores.|
|alphaNumeric||The value must be entirely alpha-numeric characters.|
|alphaUnderscore||The value must be entirely alpha-numeric, with underscores but not dashes.|
|array||The value must be a valid array object.|
|base64||The value must be a base64 encoded value.|
|between:min:max||The value must have a size between the given min and max.|
|contains:value||The value must contain the value. For a string, it does an "indexOf" check, an array "_.indexOf" and for an object "_.has".||date||The value must be a valid date object.|
|different:fieldName||The given field must be different than the `fieldName` under validation.|
|The field must be a valid formatted e-mail address.|
|empty||The value under validation must be empty; either an empty string, an empty, array, empty object, or a falsy value.|
|exactLength:value||The field must have the exact length of "val".|
|exists||The value under validation must not be undefined.|
|finite||The value under validation must be a finite number.|
|function||The value under validation must be a function.|
|greaterThan:value||The value under validation must be "greater than" the given value.|
|greaterThanEqualTo:value||The value under validation must be "greater than" or "equal to" the given value.|
|integer||The value must have an integer value.|
|ipv4||The value must be formatted as an IPv4 address.|
|ipv6||The value must be formatted as an IPv6 address.|
|lessThan:value||The value must be "less than" the specified value.|
|lessThanEqualTo:value||The value must be "less than" or "equal to" the specified value.|
|luhn||The given value must pass a basic luhn (credit card) check regular expression.|
|matchesField:fieldName||The value must exactly match the value of another `fieldName` under validation.|
|max:value||The value must be less than a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.|
|maxLength:value||The value must have a length property which is less than or equal to the specified value. Note, this may be used with both arrays and strings.|
|min:value||The value must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.|
|minLength:value||The value must have a length property which is greater than or equal to the specified value. Note, this may be used with both arrays and strings.|
|NaN||The value must be NaN.|
|natural||The value must be a natural number (a number greater than or equal to 0).|
|naturalNonZero||The value must be a natural number, greater than or equal to 1.|
|null||The value must be null.|
|numeric||The value must have a numeric value.|
|object||The value must pass an _.isObject check.|
|plainObject||The value must be an object literal.|
|required||The value must be present in the input data.|
|url||The value must be formatted as an URL.|
|uuid||Passes for a validly formatted UUID.|
Sometimes you may wish to require a given field conditionally, for example require a field only if another field has a greater value than 100. Or you may need two fields to have a given value only when another field is present. Adding these validation rules doens't have to be a pain. First, create a
Checkit instance with the main rules that never change:
var checkit =firstName: 'required'lastName: 'required'email: 'required' 'email';
Then use the
maybe method to add additional rules:
The first of the
maybe method is the hash of validation fields / settings, similar to the main
Checkit object. The second argument is a function, evaluated with the object being validated, and if it returns explicitly
true or with a promise fulfilling with
true, it will add an additional validator to the
This method makes building complex conditional validations a snap.
// In this example, the "authorBio" field is only required if there are// more than 5 books specified in the input objectcheckitmaybeauthorBio: 'required' 'max:500'return inputbooks > 5;;
First, and simplest, you can specify a function on the validation array for a property. For example:
email: 'email'return knex'accounts'where'email' '=' valthenif resplength > 0 throw 'The email address is already in use.'
You may also specify an object in one of the validator slots, specifying at the minimum a rule, and optionally params, label, and message.
email:rule: 'email'label: 'Email'first_name:rule: 'required'message: 'You must supply a first name value!!'rule: 'minLength:3'label: 'first name of this application'arr:rule: 'contains'params: 10 // Number => Different behavior than "contains:10"
You may also use the
context parameter passed to
run when using a function on the validation array of a property. This can be particularly useful if your validation function needs to execute within a transaction:
email:var query = knex'users';if context && contexttransactingquerytransactingcontexttransacting;return querywhere'email' '=' valandWhere'id' '<>' thistargetidthenif resplength > 0throw 'The email address is already in use.';;
Second, you may add a custom validator to the
Checkit.Validators object, returning a boolean value or a promise.
return knextablewherecolumn '=' valthenif resplength > 0throw 'The ' + table + '.' + column + ' field is already in use.';;email: 'email' 'unused:accounts:email'
One of the main features of
Checkit is the error handling; By extending the error object with utility methods from underscore, the errors are even easier to work with.
The main Error object,
Checkit.Error is returned from the has several helper methods & properties, as well as a number of utility methods:
The "errors" property of a
Checkit.Error object is a hash of errors for each of the fields which are considered "invalid" in any way by the validation rules. The keys in this hash are the invalid fields, and the values are Checkit.FieldError objects, which in-turn have an
errors attribute, an array containing errors for each failed rule.
get method returns the
Checkit.FieldError object for a specific key, or
undefined if one does not exist.
Useful for debugging, the
toString method converts the
Checkit error into a human readable representation of the failed validation. If the
flat argument is passed as a "truthy" value, it will output only the first
ValidationError in the
FieldError; otherwise it will output each validation message in a comma separated string.
Converts the current error object to a json representation of the error, for easy use/refinement elsewhere. For other methods, such as map, reduce, each, see the utility methods section.
FieldError is an error that contains all of the sub-errors for the validation of an individual item in the validated hash.
errors property of a
ValidationError is the result of an individual error in the field rule.
The following methods are underscore methods proxied to the
Checkit.FieldError objects, for easy manipulation of the
.errors object contained in each.
Checkit.labelTransform method takes a function that receives the field name and returns a human-readable label for use in error messages.
CheckItis now renamed
targetarguments, so the syntax is now
Checkit(input).run(validations), allowing for re-use of the validation objects.