als-validator
v0.8.0
Published
Small class for frontend and backend fields validation
Downloads
4
Maintainers
Readme
Validator
About
Validator is a small JavaScript class for frontend and backend (node.js). The class validate if data inside object match the requirements.
v07 - change log
- Validator return object
{errors:0,field:[errors]}
insted array[errors]
. Now each field gets it's errors and errors.errors counts the sum of errors (0 by default). - Now you can add spaces to field in arror output by adding _ in variable name. For example
answer_1:'required'
will returnThe answer 1 can't be empty
.
Example:
let data = {
email:'[email protected]',
password:'q6we4r%ty',
url:'alex.com',
json:'{"age":"20"}'
}
let obj = {
email:'email',
password:'min:7|required|symbols|nums:3',
url:'url',
json:'json'
}
let errors = new Validator(obj,data).run()
console.log(errors) // Output: {password:[0: "The password has to contain at least 3 number characters"]}
Validation rules
List of validation rules for run method
- required - checks if field is empty or null
- email - checks if field is an email
- lowers:times - checks if field has lowercase characters * times
- uppers:times - checks if field has uppercase characters * times
- nums:times - checks if field has numeric characters * times
- symbols:times - checks if field has special symbol characters * times
- url - checks if field is an url
- json - checks if field is a valid json
- unique - checks if field has no repeated characters
Method which use the async method and model
- confirm:field2 - checks if field's value = field2's value
- exists:tableName - checks if field's value exist in given table in db
- notexists:tableName - checks if field's value not exist in given table in db
- password:tableName - checks if field's value matches value in given table in db
- If req.data containes id, the match check will occure only at id
- If req.data not containes id field, the match check will occure in all recordes in a table
Basics
Validator is a class and it's constructor gets two parameters: obj and data.
- obj - is an object with ruels for validation
- data - is an object with data for validation
- model - model is an als-model object
The syntax:
let errors = new Validator(obj,data).run()
let errors = new Validator(obj,data,model).async()
The run method, runs loop for checking each field in obj and validate fields from data. If all fields pass validation, it returns empty array. Else, it returns array with errors.
data
Data has to be json with {field:value,field:value}
format. Value has to be string.
obj
The object has to be with {field:rules,field:rules}
format.
The rules are separetad by | and parameter separated with :.
For example:
let data = {password:"aaa333$F"}
let obj = {password:"unique|num|uppers:2|symbols|required"}
let errors = new Validator(obj,data).run()
console.log(errors)
// The output:
// [
// errors:2,
// password: [
// 0: "The aaa333$F has repeated characters"
// 1: "The password has to contain at least 2 uppercase characters"
// ]
// ]
The example above checking password field "aaa333$F"
for:
- unique - repeated characters
- num - at least one numeric character
- apper:2 - at least two uppercase characters
- symbols - at least one special symbol character
- required - the field is not empty
Customize errors
All errors placed as functions inside Validator.$errors. There are two ways to customize errors:
- Go to node_modules\validate.js and change the error content to what ever you want
- Create new Validator object and then change the errors content on new object.$errors
Model and async method on node.js
To use model, you need to install als-model
and create new model object with sqlite or mysql data base.
For example, you can do the folowing:
npm i als-model
const {join} = require('path')
let conData = join(__dirname,'db','data.sqlite3')
let model = new Model(conData)
Then you create the tables and migrate it, you can use this model with Validator async method.
async function auth() {
let errors = await new Validator(obj,data,model).async()
}
form method and ajax validation
form method grabbing all input data (name:value) from input and select fields by listening to event.
form method has 3 parameters: id of form, event for listening and validation on loading page (false by default).
Syntax: form(formId,event,validateOnLoad = false)
- formId - id of form for grabbing the data
- event - any js event like input (oninput), change(onchange),..
- validateOnLoad - by default validation starts only if event occurs. By setting 3d parameter as true, you start validation on load too.
Errors:
In case of validation errors, you can publish them just by giving to element id with name of input field with addition of -error. For example if you have input field with name 'some' - <input type="text" name="some">
then element with id 'some-error' will get innerHtml = validationErrors.
<form action="/register" method="POST" id="register-form">
<div><input class="input" type="email" name="email"></div>
<small><div class="pl2 t-red" id="email-error"></div></small>
<div><input class="input" type="text" name="username"></div>
<small><div class="pl2 t-red" id="username-error"></div></small>
<div><input class="input" type="password" name="password" id="password" ></div>
<small><div class="pl2 t-red" id="password-error"></div></small>
<div><input class="input" type="password" name="confirm" id="confirm"></div>
<small><div class="pl2 t-red" id="confirm-error"></div></small>
<button class="m2" type="submit" id="register">Register</button>
</form>
<script src="validate.js"></script>
<script>
new Validator({
email: 'email|ajax',
confirm:'confirm:password',
password: 'min:7|required|num',
username: 'min:3'
}).form('register-form','input',true)
</script>
if(isset($_SERVER['HTTP_AJAX'])) {
// do some validation
return json_encode($errors);
}
Ajax validation
For ajax validation, you need to install als-ajax
.
If you put on any place of validation rules ajax, on every event, will be sent ajax request to server. The ajax request will be to form action and by form method.
After ajax validation, als-validator get response from server and trying to convert it to json. If json has names of fields, with errors array, errors are added to other errors.