Vanilla javascript form validation micro-library
{:.hide}
~4kb minified, ~2kb gzipped, no dependencies
Some examples of use can be found here.
Include the javascript file in your html head or just before the closing body tag
Now create some form and validate
window.onload = function () {var form = document.getElementById("form1"); // create the pristine instance var pristine = new Pristine(form); form.addEventListener('submit', function (e) { e.preventDefault(); // check if the form is valid var valid = pristine.validate(); // returns true or false });
};
That's it
It automatically validates
required, min, max, minlength, maxlengthattributes and the value of type attributes like
email, numberand more..
Pristinetakes
3parameters
form The form element
config An object containing the configuration. Default is bootstrap's configuration which is
let defaultConfig = { // class of the parent element where the error/success class is added classTo: 'form-group', errorClass: 'has-danger', successClass: 'has-success', // class of the parent element where error text element is appended errorTextParent: 'form-group', // type of element to create for the error text errorTextTag: 'div', // class of the error text element errorTextClass: 'text-help' };
true
$ npm install pristinejs --save
pristine.addValidator(nameOrElem, handler, errorMessage, priority, halt);
var pristine = new Pristine(document.getElementById("form1"));var elem = document.getElementById("email");
// A validator to check if the first letter is capitalized pristine.addValidator(elem, function(value) { // here
this
refers to the respective input element if (value.length && value[0] === value[0].toUpperCase()){ return true; } return false; }, "The first character must be capitalized", 2, false);
// A validator to check if the input value is within a specified range // Global validators must be added before creating the pristine instancePristine.addValidator("my-range", function(value, param1, param2) { // here
this
refers to the respective input element return parseInt(param1) <= value && value <= parseInt(param2)}, "The value (${0}) must be between ${1} and ${2}", 5, false);
Now you can assign it to your inputs like this
Add an attribute like
data-pristine--messagewith the custom message as value to show custom error messages. You can add custom messages like this for as many validators as you need. Here
ValidatorNamemeans
required,
min,
maxetc.
| Name | Usage | Description| | --- | ---- | ----- | |
required|
requiredor
data-pristine-required| Validates required fields| |
type="email"or
data-pristine-type="email"| Validates email| |
number|
type="number"or
data-pristine-type="number"| | |
integer|
data-pristine-type="integer"| | |
minlength|
minlength="10"or
data-pristine-minlength="10"| | |
maxlength|
maxlength="10"or
data-pristine-maxlength="10"| | |
min|
min="20"or
data-pristine-min="20"| | |
max|
max="100"or
data-pristine-max="100"| | |
pattern|
pattern="/[a-z]+$/i"or
data-pristine-pattern="/[a-z]+$/i",
\must be escaped (replace with
\\) || |
equals|
data-pristine-equals="#field-selector"| Check that two fields are equal |
Pristine(form, config, live)
Constructor
| Parameter | Default | Required? | Description| | --- | ---- | ----- | ---- | |
form| - |
config| See above|
live|
true|
pristine.validate(inputs, silent)
Validate the form or field(s)
| Parameter | Default | Required? | Description| | --- | ---- | ---- | --- | |
inputs| - |
document.getElement...,
document.querySelector...or even
jquerydom| |
silent|
false|
silentis
true|
pristine.addValidator(elem, fn, msg, priority, halt)
Add a custom validator
| Parameter | Default | Required? | Description| | --- | ---- | ----- | --- | |
elem| - |
fn| - |
fn("myValue", 10, 20, "dhaka"). Inside the function
thisrefers to the input element| |
message| - |
${0}for the input's value,
${1}and so on are for the attribute values. For the above example,
${0}will get replaced by
myValue,
${1}by
10,
${2}by
20,
${3}by
dhaka. It can also be a function which should return the error string. The values and inputs are available as function arguments| |
priority| 1 |
halt|
false|
trueafter validating the current validator, rest of the validators are ignored on the current field.|
Pristine.addValidator(name, fn, msg, priority, halt)
Add a global custom validator
| Parameter | Default | Required? | Description| | --- | ---- | ----- | --- | |
name|
data-pristine-attribute in form fields to apply this validator| |
....| - | - | Other parameters same as above |
pristine.getErrors(input)
Get the errors of the form or a specific field
| Parameter | Default | Required? | Description| | --- | ---- | ----- | --- | |
input| - |
inputis given, it returns the errors of that input element, otherwise returns all errors of the form as an object, using input element as key and corresponding errors as value.
validate()must be called before expecting this method to return correctly.|
pristine.addError(input, error)
Add A custom error to an input element
| Parameter | Default | Required? | Description| | --- | ---- | ----- | --- | |
input| - |
error| - |
pristine.setGlobalConfig(config)
Set the global configuration
| Parameter | Default | Required? | Description| | --- | ---- | ----- | --- | |
config| - |
Pristine.setLocale(locale)
Set the current locale globally
| Parameter | Default | Required? | Description| | --- | ---- | ----- | --- | |
locale| - |
Pristine.addMessages(locale, messages)
Set the current locale globally
| Parameter | Default | Required? | Description| | --- | ---- | ----- | --- | |
locale| - |
messages| - |
pristine.reset()
Reset the errors in the form
pristine.destroy()
Destroy the pristine object
The goal of this library is not to provide every possible type of validation and thus becoming a bloat. The goal is to provide most common types of validations and a neat way to add custom validators.