0.6.0 • Published 7 months ago

confirm-json v0.6.0

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

confirm-jsonconfirm-json

confirm-jsonconfirm-json

The confirm-jsonconfirm-json package is designed to be used with Express and other backend frameworks to validate JSON objects sent from the browser. It ensures that incoming data meets all specified requirements before it is saved to the database. By utilizing this package, developers can enforce data integrity, reduce errors, and enhance the security of their applications by preventing invalid or malicious data from being processed.

Developers define validation rules using rules.add to create one or more sets of rules. When declaring an app.post or app.put route, developers can utilize the middleware function provided by confirm-jsonconfirm-json to validate incoming requests. This middleware will attach a req.errors property to the request object, allowing route handlers to check for validation success and report any errors back to the user.

Section: Adding Rules Rules are added using rules.add(name, [array of strings]), where each string is a comma-separated value that includes the following parameters:

  • name: The name of the field to validate.
  • type: The data type to validate against.
  • required/optional: Indicates if the field is required or optional.
  • default: A default value if the field is not provided.
  • Other parameters specific to the data type, as applicable.
    Section: Predefined Types The package comes with support for the following predefined types:
  • authRole: An enumeration that validates user roles, with default values of guest, subscriber, and admin. This can be configured by adding an AUTH_ROLE environment variable, such as AUTH_ROLE=Guest,Student,Teacher,Admin, which would override the default roles for the authRole data type.
  • boolean: Ensures the value is a boolean.
  • compare: Compares values for equality.
  • date: Validates date formats, which must be in the form "yyyy-mm-dd."
  • email: Ensures the value is a valid email address.
  • enum: Checks if the value is within a specified set of allowed values.
  • float: Validates floating-point numbers. Two optional parameters are the minimum and maximum values.
  • integer: Validates integer values. Two optional parameters are the minimum and maximum values.
  • password: Validates password complexity. The following environment variables can be used to override the default configuration for password verifications:
    • PASSWORD_MIN_LENGTH: Minimum length of the password (default is 8).
    • PASSWORD_MIN_UPPER: Minimum number of uppercase letters (default is 1).
    • PASSWORD_MIN_LOWER: Minimum number of lowercase letters (default is 1).
    • PASSWORD_MIN_DIGIT: Minimum number of digits (default is 1).
    • PASSWORD_MIN_SYMBOL: Minimum number of symbols (default is 1).
  • regex: Validates against a regular expression.
  • string: Ensures the value is a string, with optional minimum and maximum length.
  • time: Validates time formats.

Additionally, developers can use the types object to add or update any custom data types they need, allowing for conversion from a string (part of the rules) to a custom validator.
Section: Adding Enumerations New enumerations can be added using the enums.add method. For example:

  • To add a gender enumeration: enums.add("gender", "Male,Female,Non-Binary");
  • To add an education enumeration: enums.add("Education", "High School,GED,Bachelor,Master,Doctorate");

Enumerations can also be updated using the enums.update function to modify existing values as needed.
Example

const jsonRules = require("confirm-jsonconfirm-json");

// Define rules
const rules = jsonRules.rules();
const authRoleRules = [
  "firstname,string,required,,1,20",
  "lastname,string,required,,1,20",
  "email,email,required,,1,80",
  "confirmEmail,confirm,required,,email",
  "password,password,required,,8,40",
  "confirmPassword,confirm,,password",
  "dob,date,optional,,",
  "gpa,float,optional,0.0,0.0,4.0",
];
rules.add("myRulesForAddUser", authRoleRules);

// Example usage with Express
app.post("/api/user", rules.middleware("myRulesForAddUser"), (req, res) => {
  if (req.errors) {
    return res.status(400).json({ errors: req.errors });
  }

  // Proceed to save valid data to the database
});

Functions

add(title, rules) ⇒ Object

Adds a named array of rules to the registry.

Kind: global function
Returns: Object - - The newly parsed rules object.
Throws:

  • Error - Throws an error if rules with the specified title are already registered.
ParamTypeDescription
titlestringThe title of the rules to add.
rulesArray.<string>An array of rule strings to add.

find(title) ⇒ Object | undefined

Finds the specified titled rules in the registry.

Kind: global function
Returns: Object | undefined - - Returns the rules object if found, otherwise undefined.

ParamTypeDescription
titlestringThe title of the rules to find.

middleware(title) ⇒ function

Middleware function used when data validation is needed.

Kind: global function
Returns: function - - Express middleware function.

ParamTypeDescription
titlestringThe title of the rules to use for validation.

validate(title, data) ⇒ Array.<string>

Validates the data using specified rules.

Kind: global function
Returns: Array.<string> - - An array of error messages, if any.
Throws:

  • Error - Throws an error if the specified set of rules is not defined.
ParamTypeDescription
titlestringThe title of the rules to validate against.
dataObjectThe data object to validate.

types

Module for managing predefined data types and their validators.

This module provides a set of predefined data types that can be used in validation rules. Each data type is associated with a specific validator function that follows the convention: the first part of the parser function name corresponds to the type string specified in the rules.

Predefined Data Types:

  • authRole: Validator for authentication roles.
  • boolean: Validator for boolean values.
  • compare: Validator for comparing values.
  • date: Validator for date values.
  • email: Validator for email addresses.
  • enum: Validator for enumerated values.
  • float: Validator for floating-point numbers.
  • integer: Validator for integer values.
  • password: Validator for password strength.
  • regex: Validator for regular expressions.
  • string: Validator for string values.
  • time: Validator for time values.

Use the validate function to validate data against a specified rule using the appropriate validator. The rule.type must match one of the predefined types listed above.

types~add(type, validator)

Adds a type handler to the global list.

Kind: inner method of types
Throws:

  • Error If the type is already defined.
ParamTypeDescription
typestringThe type to add.
validatorfunctionThe validator function associated with the type.

types~find(type) ⇒ Object | undefined

Searches the global list of type handlers for the specified type.

Kind: inner method of types
Returns: Object | undefined - The type handler object if found, otherwise undefined.

ParamTypeDescription
typestringThe type to search for.

types~remove(type)

Removes the specified type handler from the global array.

Kind: inner method of types

ParamTypeDescription
typestringThe type to remove.

types~update(type, validator)

Updates a predefined type parser.

Kind: inner method of types
Throws:

  • Error If the type is not defined.
ParamTypeDescription
typestringThe type to update.
validatorfunctionThe new parser function.

types~validate(rule, data, errors) ⇒ *

Validates data against a specified rule using a validator function.

Kind: inner method of types
Returns: * - Returns the result of the validation.
Throws:

  • Error Throws an error if the type specified in rule is not defined.
ParamTypeDescription
ruleObjectThe rule object containing type and validator.
data*The data to be validated.
errorsArrayArray to store validation errors.

Functions

add(name, values)

Adds a new enumerated type.

Kind: global function

ParamTypeDescription
namestringThe name of the enumerated type.
valuesArrayThe values associated with the enumerated type.

find(name) ⇒ Object | undefined

Finds an enumerated type by name.

Kind: global function
Returns: Object | undefined - - Returns the enumerated type object if found, otherwise undefined.

ParamTypeDescription
namestringThe name of the enumerated type to find.

remove(name)

Removes an enumerated type by name.

Kind: global function
Throws:

  • Error - Throws an error if the enumerated type does not exist.
ParamTypeDescription
namestringThe name of the enumerated type to remove.

update(name, values)

Updates the values of an existing enumerated type.

Kind: global function
Throws:

  • Error - Throws an error if the enumerated type does not exist.
ParamTypeDescription
namestringThe name of the enumerated type to update.
valuesArrayThe new values for the enumerated type.

Functions

valueValidator(rule, data, parser, errors) ⇒ boolean

Validates the value against the specified rule and data.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object containing the property name and validation settings.
dataObjectThe data object to validate, which should contain the property specified in the rule.
parserfunctionThe parser function to convert the data value.
errorsArray.<string>Array to collect validation error messages.

authRoleValidator(rule, data, errors) ⇒ boolean

Validates an authentication role field.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.

booleanValidator(rule, data, errors) ⇒ boolean

Validates a boolean field.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.

compareValidator(rule, data, errors) ⇒ boolean

Compares a specified data property with another for validation. Throws an error if the comparison property name is missing or invalid.

Kind: global function
Returns: boolean - Returns true if the values are the same, otherwise false.
Throws:

  • Error Throws an error if the comparison property name is missing or invalid.
ParamTypeDescription
ruleObjectThe validation rule containing parameters.
dataObjectThe data object containing values to be compared.
errorsArray.<string>An array to collect error messages.

dateValidator(rule, data, errors) ⇒ boolean

Validates a date field.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.

emailValidator(rule, data, errors) ⇒ boolean

Validates an email field.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.

enumValidator(rule, data, errors) ⇒ boolean

Validates a value against a set of enumerated options.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.
Throws:

  • Error - Throws an error if the enum validator is not implemented.
ParamTypeDescription
ruleObjectThe validation rule object containing the enum parameters.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.

floatValidator(rule, data, errors) ⇒ boolean

Validates a floating-point number field.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.

integerValidator(rule, data, errors) ⇒ boolean

Validates an integer field.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.

passwordValidator(rule, data, errors) ⇒ boolean

Validates a password field.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.

regexValidator(rule, data, errors) ⇒ boolean

Validates a value in the data object against a regular expression specified in the rule.

Kind: global function
Returns: boolean - - Returns true if the value matches the regex, otherwise false.
Throws:

  • Error - Throws an error if the regex is not provided or invalid.
ParamTypeDescription
ruleObjectThe validation rule object.
rule.namestringThe name of the rule, used as the key in the data object.
rule.paramsArrayThe parameters for the rule, where the first element is the regex.
dataObjectThe object containing values to validate.
errorsObjectAn object to accumulate error messages.

stringValidator(rule, data, errors) ⇒ boolean

Validates a string field.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.

timeValidator(rule, data, errors) ⇒ boolean

Validates a time field.

Kind: global function
Returns: boolean - - Returns true if validation succeeds, false otherwise.

ParamTypeDescription
ruleObjectThe validation rule object.
dataObjectThe data object to validate.
errorsArray.<string>Array to collect validation error messages.