sm-form-validation
A simple JS form Validation, for projects using Node.
Installation
Install with NPM.
npm install sm-form-validation
Simple Usage
const validate required email = // import the validate function and the validations
The Validation Function
It receives an array of objects, that contains the value to validate and a validation array.
Then return a Promise that return empty when success or a array when has an error
The Error Return
When the validation gets error, it return an Array with all the occurrences.
This code:
Will return this Array:
value: '' // Value to validate index: 0 // index on value array validation: Function: validateRequired // Validation Type status: 'The field is required' // The default error message
Custom Error Messages
For each validation, you can pass a custom error message as a param in the function.
Condition
For each object value, you can pass a condition to set if the validation gonna run or not as a second Key, called condition.
As a value of condition you have to pass an object with the values that you want to compare on the respectively order.
let usingEmail = true // this variable gonna be the trigger to validate or not the email field
In the code below we have two examples:
The email gonna validate and throw an error:
The name will not start validation:
let usingEmail = true // this variable gonna be the trigger to validate or not the email fieldlet usingName = false // this variable gonna be the trigger to validate or not the name field
The Return
value: 'contatosmolski@gmail' // it only validates the email index: 0 validation: Function: validateEmail status: 'Wrong email'
Validations
Name | Sintax | Description |
---|---|---|
Required | required( ' Custom Message ' ) | Validate the length of the value or if value is undefined or null |
Custom | custom( customValue, ' Custom Message ' ) | Validate a custom passed value |
email( ' Custom Message ' ) | validate a string by an email valid Regex | |
Minmax | minmax( minVal ,maxVal ,[ 'Min Custom Message', 'max Custom Message' ] ) | Validate a value by the min and the max value passed |
Cpf | cpf( 'Custom Message' ) | Validate a document by a valid Regex |
Cnpj | cnpj('Custom Message' ) | Validate a document by a valid Regex |