Pristine Documentation

repository·master·Indexed 19 days ago

https://github.com/sha256/pristine

A lightweight (~4kb minified), dependency-free vanilla JavaScript library for form validation. Pristinejs provides built-in support for HTML5 validation attributes and allows for the creation of custom global or field-specific validators.

Tokens
1.9K
Snippets
8
Records
8
Agent score
16%

What's inside Pristine

  1. Customize error messages for built-in validators

    master

    You can override default error messages for any validator (including built-in ones) by adding a data-pristine-<ValidatorName>-message attribute to the input element. Replace <ValidatorName> with the name of the validator (e.g., required, email, min, max).

    <!-- Custom message for the 'required' validator -->
    <input required data-pristine-required-message="My custom message"/>
    
    <!-- Custom message for the 'email' validator -->
    <input type="email" data-pristine-email-message="Please enter a valid email address"/>
  2. Initialize and use Pristine for form validation

    master

    To use Pristine, include the script in your HTML, then instantiate Pristine by passing the form element. You can then call .validate() during form submission to check if the form is valid.

    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
    
        });
    };
  3. Add a custom validator to a specific field

    master

    Use pristine.addValidator() on a specific DOM element to apply validation logic only to that field. Inside the handler function, this refers to the input element.

    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);
  4. Add a global custom validator

    master

    To create a validator that can be reused across multiple fields via data attributes, use the static Pristine.addValidator() method. Note: Global validators must be added before creating the Pristine instance.

    Once added, apply it to an input using data-pristine-<NAME>="param1,param2".

    // 1. Define the global validator
    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);
    
    // 2. Use it in HTML
    // <input type="text" data-pristine-my-range="10,30" />
  5. Configure the Pristine instance

    master

    The Pristine constructor accepts three parameters:

    1. form: The form element.
    2. config: An object containing configuration for CSS classes and error text elements. Defaults to Bootstrap configuration.
    3. live: A boolean indicating whether to validate as the user types (defaults to true).

    Default configuration object:

    let defaultConfig = {
        classTo: 'form-group',           // class of the parent element where error/success class is added
        errorClass: 'has-danger',       // error class
        successClass: 'has-success',    // success class
        errorTextParent: 'form-group',  // class of the parent element where error text element is appended
        errorTextTag: 'div',            // type of element to create for the error text
        errorTextClass: 'text-help'     // class of the error text element 
    };
    // Example instantiation with custom config
    var pristine = new Pristine(form, { 
        errorClass: 'my-error-class' 
    }, false);
  6. Pristine API Reference

    master

    Detailed method signatures for the Pristine instance and static methods.

    // Constructor
    Pristine(form, config, live)
    
    // Instance Methods
    pristine.validate(inputs, silent)
    pristine.getErrors(input)
    pristine.addError(input, error)
    pristine.reset()
    pristine.destroy()
    
    // Static Methods
    Pristine.addValidator(name, fn, msg, priority, halt)
    Pristine.setGlobalConfig(config)
    Pristine.setLocale(locale)
    Pristine.addMessages(locale, messages)
  7. Reference built-in validators

    master

    Pristine provides several built-in validators that can be triggered via HTML attributes or data-pristine-* attributes.

    | Name | Usage  | Description|
    | ---  | ----   | ---- |
    | `required` | `required` or `data-pristine-required` | Validates required fields|
    | `email` | `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 |