form-validator-simple
v0.1.1
Published
Very small form validator.
Downloads
6
Readme
javascript-form-validator
Very small form validator.
Usage
Create a form and add fields insite div
tags. You can add div
tags with
data-error
right next to the input to display error messages.
options.regexes
An object of regexes to validate all the inputs.
options.errors
An object of error messages to show when inputs are invalid. There is a default
value which is displayed when no options.errors
matches with
input[data-validation]
and no input[data-validation-error-msg]
is present.
options.onFormValidate
This callback is called whenever an input is validated.
input[data-validation]
If this attribute is present validation is activated on the input. You can either set an empty value or a value that corresponds with the regexes and errors option on the validator.
input[data-validation-regex]
The regex that checks validation of the input. Use options.regexes
for
global settings.
input[data-validation-error-msg]
The error message shown in the div[data-error]
. Use options.errors
for
global settings.
HTML:
<form action="">
<div class="form-group">
<label>Required:</label>
<input
type="text"
data-validation
required>
<div data-error></div>
</div>
<div class="form-group">
<label>Required Email Address:</label>
<input
type="text"
data-validation="email"
required>
<div data-error></div>
</div>
<div class="form-group">
<label>Required Phone Number:</label>
<input
type="text"
data-validation="regex"
data-validation-error-msg="Not valid"
data-validation-regex="^([0-9,\+]+)$">
<div data-error></div>
</div>
<button>Submit</button>
</form>
Javascript:
import Validator from '../src'
const validator = new Validator({
errors: {}, // List of error messages that correspond with data-validation
regexes: {}, // List of regexes that correspond with data-validation
onFormValidate: (isFormValid, form) => {
form.querySelector('button').disabled = !isFormValid
} // Callback that is called whenever a field is validated
})
validator.initAll()