New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

pristinejs

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pristinejs

A tiny vanilla javascript form validation library

  • 1.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
3.8K
decreased by-15.44%
Maintainers
1
Weekly downloads
 
Created
Source

Pristine - Vanilla javascript form validation library

{:.hide}

~4kb minified, ~2kb gzipped, no dependencies

Living demo

Some examples of use can be found here.

Usage

Include the javascript file in your html head or just before the closing body tag

<script src="dist/pristine.js"  type="text/javascript"></script>

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, maxlength attributes and the value of type attributes like email, number and more..

Pristine takes 3 parameters

  • 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' 
};
  • live A boolean value indicating whether pristine should validate as you type, default is true

Install

$ npm install pristinejs --save

Custom Validator

pristine.addValidator(nameOrElem, handler, errorMessage, priority, halt);

Add a custom validator to a field

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);

Add a global custom validator

// A validator to check if the input value is within a specified range
// Global validators must be added before creating the pristine instance

Pristine.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

<input type="text" class="form-control" data-pristine-my-range="10,30" />

Add custom error messages

<input required data-pristine-required-message="My custom message"/>

Add an attribute like data-pristine-<ValidatorName>-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 ValidatorName means required, email, min, max etc.

Built-in validators

NameUsageDescription
requiredrequired or data-pristine-requiredValidates required fields
emailtype="email" or data-pristine-type="email"Validates email
numbertype="number" or data-pristine-type="number"
integerdata-pristine-type="integer"
minlengthminlength="10" or data-pristine-minlength="10"
maxlengthmaxlength="10" or data-pristine-maxlength="10"
minmin="20" or data-pristine-min="20"
maxmax="100" or data-pristine-max="100"
patternpattern="/[a-z]+$/i" or data-pristine-pattern="/[a-z]+$/i", \ must be escaped (replace with \\)
equalsdata-pristine-equals="#field-selector"Check that two fields are equal

API

Pristine(form, config, live)
Constructor

ParameterDefaultRequired?Description
form-The form element
configSee aboveThe config object
livetrueWhether pristine should validate as you type

pristine.validate(inputs, silent)
Validate the form or field(s)

ParameterDefaultRequired?Description
inputs-When not given, full form is validated. inputs can be one DOM element or a collection of DOM elements returned by document.getElement..., document.querySelector... or even jquery dom
silentfalseDoes not show error messages when silent is true

pristine.addValidator(elem, fn, msg, priority, halt)
Add a custom validator

ParameterDefaultRequired?Description
elem-The dom element where validator is applied to.
fn-The function that validates the field. Value of the input field gets passed as the first parameter, and the attribute value (split using comma) as the subsequent parameters. For example, for <input data-pristine-my-validator="10,20,dhaka" value="myValue"/>, validator function get called like fn("myValue", 10, 20, "dhaka"). Inside the function this refers to the input element
message-The message to show when the validation fails. It supports simple templating. ${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
priority1Priority of the validator function. The higher the value, the earlier it gets called when there are multiple validators on one field.
haltfalseWhether to halt validation on the current field after this validation. When true after 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

ParameterDefaultRequired?Description
name-A string, the name of the validator, you can then use data-pristine-<NAME> 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

ParameterDefaultRequired?Description
input-When input is 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

ParameterDefaultRequired?Description
input-The input element to which the error should be given
error-The error string

pristine.setGlobalConfig(config)
Set the global configuration

ParameterDefaultRequired?Description
config-Set the default configuration globally to use in all forms.

Pristine.setLocale(locale)
Set the current locale globally

ParameterDefaultRequired?Description
locale-Error messages on new Pristine forms will be displayed according to this locale

Pristine.addMessages(locale, messages)
Set the current locale globally

ParameterDefaultRequired?Description
locale-The corresponding locale
messages-Object containing validator names as keys and error texts as values

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.

License

MIT

Keywords

FAQs

Package last updated on 01 Apr 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc