Skip to content

Repository files navigation

hakim

NPM Version

A lightweight, flexible validation library for JavaScript that works in both browser and Node.js environments. https://www.npmjs.com/package/hakim

Why Hakim?

Hakim provides a powerful yet simple validation system that handles both string and numeric values with the same API. This is particularly useful for browser environments where form inputs are often strings even when representing numbers.

Key features:

  • Unified validation for strings and numbers
  • Composable validation rules for complex validations
  • Flexible logic operators (AND/OR) for combining rules
  • Extensible plugin system for custom validators
  • Modern ES module format with browser and Node.js support

Installation

To install via npm:

npm install hakim

Usage

Import Hakim in your JavaScript project:

// ESM importimportHakim,{anyOf}from'hakim';// Or in browser with script tag<scriptsrc="path/to/hakim.js"></script>

Basic Concept

The core concept of Hakim is simple:

constvalidator=newHakim(rules);validator.validate(value);// returns true or false

Where rules is an array of validation rules, and each rule consists of a validator and an operand:

[{is: "number"},{is: "integer"}]

In the above example, is is the validator and "number" is the operand. Each rule is executed in order, and all rules must pass for the validation to succeed (AND logic by default).

Key Features

  1. Unified validation for both numbers and strings
  2. Multiple rules can be combined to create complex validations
  3. Configurable logic operators (AND/OR) for rule processing
  4. Support for nested rule groups

Examples

Basic validation:

importHakimfrom'hakim';// Validate an integernewHakim([{is: "number"},{is: "integer"}]).validate(2);// truenewHakim([{is: "number"},{is: "integer"}]).validate("2");// truenewHakim([{is: "number"},{is: "integer"}]).validate(2.5);// false// Validate an emailnewHakim([{is: "email"}]).validate("user@example.com");// true

Using OR logic with anyOf:

importHakim,{anyOf}from'hakim';// Value must be empty OR a number OR an emailnewHakim(anyOf([{is: "empty"},{is: "number"},{is: "email"}])).validate("user@example.com");// true

Nested rules:

// Must be empty OR (a number AND an integer)newHakim([{is: "empty"},[{is: "number"},{is: "integer"}]]).validate("");// true

Validators

Hakim provides a rich set of validators to create expressive validation rules:

Value Type Validators

ValidatorDescription
isChecks if a value matches a predefined entity type (e.g., number, email)
isNotNegates the is validator
equalChecks if a value equals the operand (uses ==)
matchTests if a string matches a regular expression pattern
requiredChecks if a value is not empty

Number Validators

ValidatorDescription
gtGreater than
ltLess than
goeGreater than or equal
loeLess than or equal
dplacesGtDecimal places greater than
dplacesLtDecimal places less than
dlengthOfDecimal places equals

String Validators

ValidatorDescription
lengthOfString length equals
lengthGtString length greater than
lengthLtString length less than
beginWithSubString begins with a substring
notBeginWithSubString does not begin with a substring
hasStringString contains a substring

Character Set Validators

ValidatorDescription
areAll characters in string belong to a character set
existsString contains characters from a character set
startWithSetString starts with a character from a set
notStartWithSetString does not start with a character from a set

Entity Types

Entity types are used with the is and isNot validators to check if a value represents a specific type of data:

EntityDescription
numberValidates if value is a number (or string representing a number)
integerValidates if value is an integer
decimalValidates if value is a decimal number
positiveValidates if value is a positive number
negativeValidates if value is a negative number
emailValidates if value is a valid email address
emptyValidates if value is "", null, undefined or []
ipValidates if value is a valid IP address
urlValidates if value is a valid URL
stringValidates if value is a string

Example:

// Check if value is a numbernewHakim([{is: "number"}]).validate("123");// true// Check if value is an emailnewHakim([{is: "email"}]).validate("test@example.com");// true

Character Sets

Character sets are used with the are, exists, startWithSet, and notStartWithSet validators:

Character SetDescription
latinLatin letters (a-z, A-Z)
enLetterEnglish letters (same as latin)
digitNumeric digits (0-9)

Example:

// Check if all characters are digitsnewHakim([{are: "digit"}]).validate("12345");// truenewHakim([{are: "digit"}]).validate("123a5");// false// Check if string contains any digitsnewHakim([{exists: "digit"}]).validate("abc123");// true

Logic Operations

By default, Hakim processes rules with AND logic (all rules must pass), but you can change this using the anyOf function for OR logic:

AND Logic (Default)

All rules must pass for validation to succeed:

// Value must be a number AND an integernewHakim([{is: "number"},{is: "integer"}]).validate("123");// truenewHakim([{is: "number"},{is: "integer"}]).validate("123.4");// false

OR Logic

Using anyOf to enable OR logic (any rule passing means validation success):

importHakim,{anyOf}from'hakim';// Value can be either empty OR a numbernewHakim(anyOf([{is: "empty"},{is: "number"}])).validate("");// truenewHakim(anyOf([{is: "empty"},{is: "number"}])).validate("123");// true

Nested Logic Groups

You can create complex validations by nesting rule groups:

// Must be either empty OR (a number AND positive)newHakim([{is: "empty"},[{is: "number"},{is: "positive"}]]).validate("123");// true// Must be (a number AND an integer) OR (a string AND not empty)newHakim(anyOf([[{is: "number"},{is: "integer"}],[{is: "string"},{required: true}]])).validate("hello");// true

Extensions

You can extend Hakim with custom validators using the extend method:

Adding Custom Entity Types

// Add a 'binary' entity typeHakim.extend('something','binary',function(value){return/^[01]+$/.test(value);});// Now you can use it in validationnewHakim([{is: "binary"}]).validate("1010");// truenewHakim([{is: "binary"}]).validate("1234");// false

Adding Custom Character Sets

// Add a 'hex' character setHakim.extend('characterSets','hex',function(char){return/^[0-9a-fA-F]$/.test(char);});// Now you can use it in validationnewHakim([{are: "hex"}]).validate("a1f5");// true

Browser Compatibility

Hakim is designed to work in all modern browsers. The library is provided as both ES modules and CommonJS formats:

  • built/hakim.js - ES module format
  • built/hakim.cjs - CommonJS format

Testing

The library includes comprehensive test cases for both browser and Node.js environments:

# Run tests in Node.js
npm run test:node
# Run tests in browser
npm run test:browser

License

This project is licensed under the LGPL-3.0-or-later

About

a validation lib for browser environments only

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages