1.0.5 • Published 6 months ago

smart-validation v1.0.5

Weekly downloads
-
License
ISC
Repository
github
Last release
6 months ago

Smart Validation

A robust and flexible validation library for JavaScript and TypeScript, providing built-in support for various data types, custom validation rules, and error handling.


Usage

Import the Library

import { isValid, ValidationType } from "smart-validation";

Basic Validation

const rules = {
	minLength: 3,
	maxLength: 10,
	allowEmpty: false,
};

const result = isValid("Hello", ValidationType.STRING, rules);

if (result.isValid) {
	console.log("Validation passed!");
} else {
	console.log("Validation failed:", result.errors);
}

API Reference

isValid(value: any, type: ValidationType, rules: ValidationRules): ValidationResult

Parameters:

  1. value: The value to be validated.
  2. type: The expected data type. Must be one of the ValidationType enum values.
  3. rules:(Optional) An object defining validation rules and custom error messages.

Returns:

  • An object with:
    • isValid: Boolean indicating if validation passed.
    • errors: Array of error messages if validation failed.

Validation Rules

RuleTypeDescription
allowEmptybooleanWhether empty values are allowed (default: true).
minLengthnumberMinimum length for strings or arrays.
maxLengthnumberMaximum length for strings or arrays.
minValuenumber/bigintMinimum value for numbers or bigints.
maxValuenumber/bigintMaximum value for numbers or bigints.
regexPatternRegExpRegex pattern to match strings.
allowedValuesany[]Array of valid values.
prohibitedValuesany[]Array of invalid values.
requiredFieldsstring[]List of required fields for objects.
customValidatorfunctionA custom validation function that returns true or false.
customErrorsobjectCustom error messages for specific validation keys.