validate-fields-body
v1.1.11
Published
Validate-Fields-Body is a Javascript library for dealing with validation.
Downloads
73
Maintainers
Readme
Validate-Fields-Body
This is a JavaScript function that validates a given form data object against a set of validation keys. The function returns an array with three elements:
Installation
npm i validate-fields-body
The first element is a boolean value that indicates whether there are any validation errors or not. The second element is an array of strings that contains the error messages for each validation failure, or null if there are no errors. The third element is an object that contains only the valid fields from the form data, or null if there are any errors. The function performs three types of validation:
Required fields: The validation keys that have a “!” prefix indicate that the corresponding field in the form data must be present and not empty. For example, “!name” means that the name field is required. Required types: The validation keys that have a “:” suffix indicate that the corresponding field in the form data must have a specific type. For example, “age:number” means that the age field must be a number. Matching keys: The validation keys that do not have any prefix or suffix indicate that the corresponding field in the form data must exist. For example, “email” means that the email field must be present. The function loops through each validation key and checks if it matches with the form data. If not, it adds an error message to the logs array and skips to the next key. If all keys are validated successfully, it returns false for errors and copies only the valid fields to the result object.
Here is an example of how to use this function:
Example
const { useValidate } = require("validate-fields-body");
const register = (req, res) => {
// Set your fields to validate
const fieldsValidate = ["username", "email", "password", "age", "skills"];
const [InValid, logs, result] = useValidate(fieldsValidate, req.body);
if (InValid) return res.status(403).json({ success: false, message: logs });
return res.status(201).send({ success: true, data: result });
};
Require Value
const fieldsValidate = ["!username", "!email", "!password", "!age", "skills"];
Check Types
const fieldsValidate = [
"!username:string",
"!email:string",
"!password:string",
"!age:number",
"skills:object",
];
Check Length
const fieldsValidate = ["password*3-15"];
Check Email
const fieldsValidate = ["email@"];
Options
| Option | Keyword | | ----------- | --------------- | | ! | Required Value | | :[TYPE] | Check Type | | @ | Validate Emai | | *[min-max] | Validate Length |
Contributing
Thanks you!.
Donation
Buy me a coffee :)
USDT Address
0x92072439f5cf2f35defa28a4915004971de543b0
Author by: Nero Sengtianthr.