1.1.7 • Published 4 months ago

pristine-neue v1.1.7

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

Pristine Neue - Vanilla javascript form validation library

Credits

This library is a fork of prsitinejs by sha256

Living demo

Some examples of use can be found here.

This demo is from the original library, a new demo is coming soon.

Installation

$ npm install pristine-neue --save

Usage

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

<script src="path/to/file/pristine.js" type="text/javascript"></script>

Create a Pristine instance and handle the submission.

document.addEventListener('DOMContentLoaded', () => {
  var form = document.getElementById('form1');
  var pristine = new Pristine(form);

  // Handle the form submission
  form.addEventListener('submit', async (e) => {
    // The validate method return as Promise that resolves to true / false
    const valid = await pristine.validate();

    if (valid) {
      // Submit the form..
    }
  });
});

Pristine automatically validates required, min, max, minlength, maxlength, pattern attributes and the value of type attributes like email, number and more..

Pristine takes 3 parameters

  • form DOM element con containinng the fields to validate. Tipically a form element, but it can be any DOM element.
  • config An object containing the configuration. See default configuration.
  • live A boolean value indicating whether pristine should validate as you type, default is true.

Adding custom validators

You can add custom validators to a spcific pristine intance or add them globally.

Adding a custom validator to an instance

var pristine = new Pristine(document.getElementById('form'));

var elem = document.getElementById('email');

// A validator to check if the first letter is capitalized
pristine.addValidator(
  elem,
  (value) => {
    if (value.length && value[0] === value[0].toUpperCase()) {
      return true;
    }
    return false;
  },
  'The first character must be capitalized',
  2,
  false
);

Adding a global custom validator

Global validators must be added before creating the pristine instance

// A validator to check if the input value is within a specified range
Pristine.addValidator(
  'my-range',
  (value, el, param1, param2) => {
    return parseInt(param1) <= value && value <= parseInt(param2);
  },
  'The value (${0}) must be between ${1} and ${2}',
  5,
  false
);

var pristine = new Pristine(document.getElementById('form'));

Assign the new validator to inputs like this:

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

Validator Function Arguments

Validator functions receive arguments in the following order:

  1. value - The current value of the input field being validated
  2. element - The DOM element (input, select, textarea) being validated
  3. Additional parameters - These come from the data-pristine-* attributes and are processed as follows:

    • Pattern attributes (data-pristine-pattern): The entire pattern string is passed as a single argument
    • JSON values: If the attribute value is valid JSON (starts with { or [), it will be parsed and passed as a single argument
    • Regular strings: For all other cases, the attribute value is split at commas (,) and each part is passed as a separate argument

Examples:

<!-- Regular comma-separated values -->
<input data-pristine-min-max="5,10" />
<!-- Validator receives: (value, element, "5", "10") -->

<!-- Pattern value -->
<input data-pristine-pattern="/^[A-Z]+$/i" />
<!-- Validator receives: (value, element, "/^[A-Z]+$/i") -->

<!-- JSON value -->
<input data-pristine-custom-config='{"option1": true, "option2": "value"}' />
<!-- Validator receives: (value, element, {"option1": true, "option2": "value"}) -->

When creating custom validators, ensure your function accepts the appropriate number of parameters based on how you plan to configure it in HTML.

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

NameUsage
requiredrequired or data-pristine-required
emailtype="email" or data-pristine-type="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 function

ParameterDefaultRequired?Description
form-DOM element containing form fields, does not need to be a form
configSee belowConfig object
livetrueWhether pristine should validate as you type
Default configuation
{
  classTo: 'field', // Class of parent element where the error/success class is added
  errorClass: 'error' // Error class,
  successClass: 'success' // Success class,
  errorTextParent: 'field', // Class of parent element to whom the error element is appended
  errorTextTag: 'div', // Element type to create for the error text
  errorTextClass: 'error-msg', // Class of the error text element
  liveAfterFirstValitation: true, // Enable live validation only after first form submission (requires live parameter to be true)
};

Global methods

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
fn-The function that validates the field. See Validator function arguments
message-The message to show when the validation fails. If the arguments are strings, 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.

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 messages for a specific locale globally

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

Instance methids

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 error messages when silent is true

Returns a Promise that resolves to true or false

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. See Validator function arguments
message-The message to show when the validation fails. If the arguments are strings, 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.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.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

Testing

Pristine Neue uses Vitest for testing. The test suite covers core functionality, built-in validators, custom validators, and localization features.

Running Tests

# Run all tests once
npm test

# Run tests in watch mode (for development)
npm run test:watch

# Run tests with coverage report
npm run test:coverage

For more details about the test suite, see the tests/README.md file.

Continuous Integration

Pristine Neue uses GitHub Actions for continuous integration. The following workflows are set up:

  • Run Tests: Runs the test suite on every push and pull request.
  • Deploy Documentation: Builds and deploys the documentation to GitHub Pages when changes are pushed to the master branch.
  • Publish Package: Publishes the package to npm when a new release is created.
1.1.1

4 months ago

1.0.0

4 months ago

1.1.7

4 months ago

1.1.6

4 months ago

1.1.5

4 months ago

1.1.4

4 months ago

1.1.3

4 months ago

1.1.2

4 months ago

0.0.3

9 months ago

0.0.2

3 years ago

0.0.1

3 years ago