A tiny (~1KB), composable and battle-tested utility library for string validation, built in TypeScript. Typically used to check the user input in applications.
import { checkIf } from "tiny-checker";
const input = "Some input";
console.log(checkIf(input).hasMinLength(3).not().hasDigit().isValid()); // trueThis library has several built-in validators that check for specific attributes in the string input:
-
hasDigit(atLeast: number, errorMessage: string): Checks if input containsatLeastnumber of digits. Defaults to 1. -
hasLength(length: number, errorMessage: string): Checks if input has exactlengthof characters. Defaults to 0. -
hasMinLength(length: number, errorMessage: string):Checks if input has minimumlengthcharacters. Defaults to 1. -
hasMaxLength(length: number, errorMessage: string): Checks if input has maximumlengthcharacters. Defaults to 1. -
hasLowerCase(atLeast: number, errorMessage: string): Checks if input containsatLeastnumber of lower-case characters. Defaults to 1. -
hasUpperCase(atLeast: number, errorMessage: string): Checks if input containsatLeastnumber of upper-case characters. Defaults to 1. -
isEmail(errorMessage: string): Checks if input is in email format. Uses https://emailregex.com/ for validation. -
matches(regex: string | RegExp, errorMessage: string): Checks if input matches theregexpattern
There's also a special function called not() that when combined with one of the validators, it negates whatever check is going to be done by the following validator.
// Checks if input doesn't contain digits
checkIf("something").not().hasDigit().isValid(); // trueTo get the result of the validation you can use two different functions:
isValid(): Returns abooleanwith the result of the validationhasErrors(): Returns an array of strings with the error messages if they exist or an empty array otherwise.
One of the main objectives of tiny-checker is to provide a composable API that allows combining multiple validators in an intuitive way. If you're familiar with jest and other testing frameworks, you'll find this very similar:
// Check if input is a strong password
checkIf("StrongPassword123")
.hasMinLength(9)
.hasMaxLength(32)
.hasUpperCase()
.hasLowerCase()
.hasDigit()
.isValid();For each validation function it's possible to define custom error messages. This is useful to provide specific error messages for special situations or for using with different languages.
checkIf("something").hasDigit(1, "needs to be alphanumeric").hasErrors();
// ["needs to be alphanumeric"]
checkIf("something").hasDigit(1, "não contém números").hasErrors();
// ["não contém números"]By default the error messages use the function parameters where applicable. This is done by replacing the $value placeholder in the error message.
checkIf("something").hasDigit(1).hasErrors();
// ["should have at least 1 digit(s)"]
checkIf("something")
.hasDigit(2, "please add at least $value digit(s)")
.hasErrors();
// ["please add at least 2 digit(s)"]It's possible to extend the behaviour of tiny-checker by adding new validators, either with a custom implementation or installed from an external plugin.
To build a new validator you have access to the TinyCheckerBase class that provides all necessary logic to build the custom validator.
import { TinyCheckerBase, defaultValidators } from "tiny-checker";
function isUpperCase<T extends TinyCheckerBase>(
this: T,
errorMessage: string = "should be all uppercase"
): T {
return this._processValue(
(this._str.match(new RegExp(/\p{Lu}/, "gu")) || []).length >=
this._str.length,
errorMessage
);
}
export const { checkIf } = TinyCheckerBase.load({
...defaultValidators,
isUpperCase,
});This will make a new checkIf function available with the additional validator, fully typed and ready to be used in conjuction with the existing validators.
The reason why we also make defaultValidators available is because in some scenarios you might want to just use a few of the default validators so that can be done by just loading the necessary ones:
import { TinyCheckerBase, defaultValidators } from "tiny-checker";
const { hasDigit, hasLength } = defaultValidators;
export const { checkIf } = TinyCheckerBase.load({
hasDigit,
hasLength,
});Finally you can also load 3rd party validators that are available as npm packages:
import { TinyCheckerBase, defaultValidators } from "tiny-checker";
import isCreditCard from "tiny-checker-cc";
import { isZipCode } from "tiny-checker-address";
export const { checkIf } = TinyCheckerBase.load({
...defaultValidators,
isCreditCard,
isZipCode,
});Below is a list of commands you will probably find useful.
Runs the project in development/watch mode. Your project will be rebuilt upon changes. TSDX has a special logger for you convenience. Error messages are pretty printed and formatted for compatibility VS Code's Problems tab.
Your library will be rebuilt if you make edits.
Bundles the package to the dist folder.
The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).
Runs the test watcher (Jest) in an interactive mode. By default, runs tests related to files changed since the last commit.
This project was bootstrapped with TSDX.