@chrisbrocklesby/validation
v1.0.2
Published
This is a validation helper, It helps validate JSON data via a quick rule set you create.
Downloads
2
Maintainers
Readme
Validation
(This helper sets rules to validate JSON Data)
This is a validation helper, The helper sets rules to validate JSON Data and throw a validation error if rule for data is not true. This valdation helper allows you to create custom rules via regex or working with other npm modules.
Install
npm i @chrisbrocklesby/validation
Require
const validation = require('@chrisbrocklesby/validation');
Example Usage
const validation = require('@chrisbrocklesby/validation');
function exampleFunction() {
try {
const data = { name: 'Chris', email: 'useratemail.ext' };
// Note email is not valid and returns => throw validationError
validation.validate([{
isValid: validation.isRequired(data.name),
message: 'name:required',
},{
isValid: validation.isEmail(data.email),
message: 'email:invalid',
}]);
}
catch (error) {
console.log(error);
// Validation Error Returns =>
// ValidationError {
// name: 'validationError',
// messages: [ 'email:invalid' ]
// }
}
}
exampleFunction();
Built-In Validation Functions
// Note replace value with what is to be checked, returns true/false.
validation.isString(value)
validation.isNumber(value)
validation.isBoolean(value)
validation.isArray(value)
validation.isObject(value)
validation.isRequired(value)
validation.notNull(value)
validation.isPk(value)
validation.isEmail(value)
validation.isPassword(value)
Validation rules structure (Array/Object)
[{
isValid: validation.isRequired(data.name),
message: 'name:required',
},{
isValid: validation.isEmail(data.email),
message: 'email:invalid',
},{
isValid: /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(data.custom),
// Customs isValid: needs to return true/false
message: 'custom:message',
}]
Contributing
Contributions, issues and feature requests are welcome.
Authors
Chris Brocklesby
- Twitter: @ChrisBrocklesby
- Github: @ChrisBrocklesby
Show Your Support
Please ⭐️ this repository if this project helped you!
License
Copyright © 2020 Chris Brocklesby.
This project is licensed under the MIT License - see the LICENSE file for details.