Constraints form validator
This library contains list of classes that allows developers to create custom validation flows.
The main idea to have configured form with rules for each field. Each field can be validated by specific constraint.
Validation constraints inspired by Symfony Constraints.
Install
npm i constraint-validator --save
Basic usage
CommonJS module
var validator = ;var form = ; form ; var errors = form;
ESM module
; const form = ; form ; const errors = form;
Error handing
In case of form data is not valid the errors
object contains properties (related to from filed names) and array of Error objects.
'email': Error Error 'password': Error
Otherwise error
variable will be empty object {}
Data transformers
Data transformers are used to translate the data for a field into a other format and back. The data transformers act as middleware and will be executed in the same order as they were applied.
There are 2 types of data transformers:
- transformer - executes before validation process
- reverseTransformers - executes after validation process
Form data transformers
; const form = ; form // next transformers will be applied to the form data ; form; console;// Output:// {"email": "email@example.me"}
Field data transformers
; const form = ; form // next transformers will be applied to the 'email' field only ; form; console;// Output:// {"email": "email@example.me"}
Documentation
-
Form - form configuration
-
Field - form field object
-
Constraints - list of supported constraints Basic constraints:
String constraints:
Comparison constraints:
Number constraints:
Date constraints:
Choice constraints:
Financial and other Number Constraints:
Other constraints:
You can create custom constrains by using deep integration.
Dependencies
- locutus - JavaScript implementation of PHP functions
- Luxon Moment - DateTime manipulation library
- IpAddrJs - IP address manipulation library
Notes
Q: Why not exceptions?
A: See try/catch performance test
Q: Is there same logic as symfony has?
A: No, please check documentation for each constraint
TODO
- Provide
types.d.ts
for better user experience - CI/CD build flow (drop
dist
folder) - Proper package integration (get IDE autocomplete working better)
- Investigate DayJS as replacements: find a way to validate timezones.