The Form Validator provides a simple JavaScript API for managing form validation through simple configuration rules. The validation response can be used with an optional ErrorMessageRouter class to set form validation errors for each input or an error summary for the entire form.
Depending on your permissions, you may need to run the install command with sudo.
npm install @alaneicker/js-form-validator
<form id="login-form" novalidate>
<ul id="error-summary"></ul>
<label for="username"><span>*</span> Username</label>
<input type="text" name="username" id="username">
<ul data-error-for="username"></ul> <!-- error container -->
<label for="password"><span>*</span> Password</label>
<input type="text" name="password" id="password">
<ul data-error-for="password"></ul> <!-- error container -->
<button type="submit">Log In</button>
</form>Note: The error containers below the form fields are not required unless using the ErrorMessageRouter.
Script tage on page
<script src="node_modules/@alaneicker/js-form-validator/dist/index.min.js"></script>CommonJS
const formValidator = require('@alaneicker/js-form-validator');ES6 Import
import { FormValidator, ErrorMessageRouter, formToJson } from '@alaneicker/js-form-validator';const loginFormRules = {
username: [
{
validator: 'required',
message: 'Username is required',
},
],
password: [
{
validator: 'required',
message: 'Password is required',
},
],
};document.querySelector('#login-form').onsubmit = e => {
e.preventDefault();
const formValidator = new FormValidator(loginFormRules);
const form = document.querySelector('#login-form');
const formData = formToJson(new FormData(form));
const validationResponse = formValidator.validate(formData);
const errorMessageRouter = new ErrorMessageRouter(addUserForm, validationResponse.data);
errorMessageRouter
.setInputErrors()
.setErrorSummary(addUserErrorSummary);
};const formValidator = new FormValidator(loginFormRules);
const inputs = document.querySelectorAll('#login-form .input');
[].forEach.call(inputs, input => {
input.addEventListener('input', e => {
const inputData = { [e.target.name]: e.target.value };
const validationResponse = formValidator.validate(inputData);
if (typeof validationResponse !== 'undefined') {
const errorMessageRouter = new ErrorMessageRouter(form, validationResponse.data);
errorMessageRouter.setInputErrors();
}
});
});const formValidator = new FormValidator(loginFormRules);
formValidator.addValidators({
confirmPassword(value) {
return value === formData.password;
}
...
});Note: Be sure to add a validation rule for your custom validator.
The FormValidator.validate() API returns a validation response object containing validation data associated with each form field from the original form data object.
Note: Only form fields with errors return an message property.
{
"totalErrors": 2,
"data": {
"username": {
"errors": 1,
"results": [
{
"required": "invalid",
"message": "Username is required"
}
]
},
"password": {
"errors": 1,
"results": [
{
"required": "valid"
}
]
}
}
}Takes 1 required argument.
- Type: [object]
FormValidator.validate(formData)You can use the validation response to set your own custom error messaging, or you use the ErrorMessageRouter class to handle the error messaging automagically.
For each of you inputs, add an error message container.
<input type="text" name="username" id="username">
<ul class="error-container" data-error-for="username"></ul>Once your form has validated and returns a response, initialize the ErrorMessageRouter class and call the setErrors() method.
const formValidator = new FormValidator(loginFormRules);
const loginForm = document.querySelector('#login-form');
const validationResponse = formValidator.validate(formData);
const isValid = validationResponse.errors === 0;
(!isValid && new ErrorMessageRouter(loginForm, validationResponse.data).setInputErrors());That's it! The ErrorMessageRouter will find the container associated with the error and append the appropriate message text.
Takes 2 required arguments.
- Type: [object HTMLFormElement]
- Type: [object]
const validationResponse = formValidator.validate(formData);
const errorMessageRouter = new ErrorMessageRouter(
document.querySelector('#login-form'),
validationResponse.data
);Uses the valiadtion data object to set error messages for individual input fields.
errorMessageRouter.setInputErrors();Uses the valiadtion data object to set an error summary listing all errors for a form.
<ul id="error-summary" class="error-summary"></ul>const errorSummary = document.querySelector('#error-summary');
errorMessageRouter.setErrorSummary(errorSummary);