Intuitive frontend forms validator based on HTML5 attributes and a tiny bit of JavaScript.
There are a lot of form validators out there. This one aims at intuitive API and relies on extensive usage of HTML data-* attributes.
It's important to note that in order to use the validation, the required
attribute must be present on your HTML element.
Here is a demo showing how to use the validator and all built-in validation types:
npm i dator
# or
yarn add dator
or include it from unpkg.com
<script src="https://unpkg.com/dator"></script>
In your JavaScript file:
import { Validator } from 'dator';
const myForm = document.querySelector('form');
const datorSettings = {}; // see below for more details
const datorCustomTypes = {}; // see below for more details
const formValidator = new Dator(myForm, datorSettings, datorCustomTypes);
In your HTML file:
<input type="text" name="full-name" required data-validate="name" />
The constuctor accepts three arguments:
- DOM element for the form that needs to be validated (Required)
- Object with settings (Optional) - more below
- Object with custom validation types - more below
// These are the settings and their default values
const datorSettings = {
validClass: 'is--valid', // The CSS classname that will be added to a valid form element
errorClass: 'is--invalid', // The CSS classname that will be added to an invalid form element
validatedClass: 'is--validated', // The CSS classname that will be added to the validated form
watch: true, // If the validation should be applied "as-you-type"
classHolder: null, // The CSS classname of the element that should receive the `validClass` and `invalidClass`
beforeValidate: null, // A function to run before the actual form submission
onSubmit: null, // A function to run during the actual form submission
afterValidate: null // A function to run after the actual form submission
};
There are several built-in validation types:
- name
- zip
- presence
- phone
- address
- integer
- float
- credit-card
- cvc
All of these validation types represent a regular expression which is used to test the value of the form element against to.
In order to add more validatior types, use the third constructor argument as shown above.
For example, if you need to add a new zip
type:
const datorCustomTypes = {
zip: /^\d{4}$/ // Change from 5 digits to 4 digits
};
MIT