javascript-input-validator
Javascript based form validator.
Introduction
'javascript-input-validator' allows you to validate input fields e.
Installation
npm i javascript-input-validator
Features
- Easy to use
- Single line import and you're ready to go
- Avoids extra inclusion or headache to write lengthy code
Usage
import { validator } from 'javascript-input-validator';
let fieldsSchema = [
{ name: 'firstName', label: 'first name', value: firstName, min: '3', max: '6', required: true },
{ name: 'lastName', label: 'last name', value: lastName, required: true },
{ name: 'email', value: email, isEmail: true },
{ name: 'company', label: 'company', value: company, messageString: 'Please select any company.', required: true },
{ name: 'designation', value: designation, isAlpha: true },
{ name: 'phoneNumber', value: phoneNumber, isNumber: true },
{ name: 'cnic', value: cnic, isAlphaNumeric: true },
{
name: 'ntn',
value: ntn,
pattern: /^\d+(-{0,1}\d+)+$/,
messageString: 'NTN may contain only number and dashes.'
}];
let errors = validator(fieldsSchema);
if(!errors) {
Success code.
} else {
Set errors in a state or some variable from where you can access errors object.
}
Then, in an input field you can write so, for example, in case of React,
{errors.firstName &&
{errors.firstName}
}
Documentation
If there is any error, the function validator() returns an object of errors with relevant keys.
If all fields are valid, it gives false (boolean).
Options
-
name : 'Input field name.'
For example, firstName in the following line.
Any input or select field name for identification of field.
-
value : 'The value of field which you want to validate.'
The value of that particular field.
-
(Optional) label : 'Any label or field name to mention in error message.'
For example: 'first name'.
-
(Optional) messageString : 'Error message you want to display.'
It will override the default error message.
required : 'For required fields.'
isEmail : 'For validating email.'
isAlpha : 'Allows only alphabets with spaces.'
isAlphaWithDashes : 'Allows only alphabets and dashes.'
isNumber : 'Allows only numbers.'
isNumberWithDashes : 'Allows only numbers with dashes.'
isAlphaNumeric : 'Allows only alphanumerics.'
isAlphaNumericWithDashes : 'Allows only alphanumerics and dashes.'
min : 'For checking minimum length.'
max : 'For checking maximum length.'
Custom Validations
pattern : 'Any regex you want to pass for validation.'
Contribute
Any suggestions and pull request are welcome!
License
Licensed under ISC