Gathering detailed insights and metrics for validator.ts
Gathering detailed insights and metrics for validator.ts
Gathering detailed insights and metrics for validator.ts
Gathering detailed insights and metrics for validator.ts
varian-validator
Lightweight JavaScript form validation.
microframework-validator.ts
Validator.ts integration with microframework
nist-password-validator.ts
A lightweight password validator that complies with NIST guidelines.
deref-json-schema
Creates a dereferenced schema for the `@cfworker/json-schema` [Validator](https://github.com/cfworker/cfworker/blob/main/packages/json-schema/src/validator.ts). Traverses schema and calls `Validator.addSchema` with the schema from each unique local file p
npm install validator.ts
Typescript
Module System
Node Version
NPM Version
TypeScript (99.81%)
JavaScript (0.19%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
11,471 Stars
1,102 Commits
826 Forks
68 Watchers
2 Branches
117 Contributors
Updated on Jul 12, 2025
Latest Version
0.2.2
Package Id
validator.ts@0.2.2
Size
27.41 kB
NPM Version
3.3.12
Node Version
5.4.1
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
Allows to use decorator and non-decorator based validation in your Typescript classes. Internally uses validator.js to make validation and sanitization.
Install module:
npm install validator.ts --save
Use typings to install all required definition dependencies.
typings install
ES6 features are used, so you may want to install es6-shim too:
npm install es6-shim --save
if you are building nodejs app, you may want to require("es6-shim");
in your app.
or if you are building web app, you man want to add <script src="path-to-shim/es6-shim.js">
on your page.
Create your class and put some validation decorators on its properties you want to validate:
1import {Validator} from "validator.ts/Validator"; 2import {Contains, IsInt, IsLength, IsEmail, IsFQDN, IsDate} from "validator.ts/decorator/Validation"; 3 4export class Post { 5 6 @IsLength(10, 20) 7 title: string; 8 9 @Contains('hello') 10 text: string; 11 12 @IsInt({ min: 0, max: 10 }) 13 rating: number; 14 15 @IsEmail() 16 email: string; 17 18 @IsFQDN() 19 site: string; 20 21 @IsDate() 22 createDate: Date; 23 24} 25 26let post = new Post(); 27post.title = 'Hello'; // should not pass 28post.text = 'this is a great post about hell world'; // should not pass 29post.rating = 11; // should not pass 30post.email = 'google.com'; // should not pass 31post.site = 'googlecom'; // should not pass 32 33let validator = new Validator(); 34let errors = validator.validate(post); // returns you array of errors
If you want to do sanitization you should use sanitize
method:
1validator.sanitize(post);
There are some additional methods you may want to use:
1validator.validateAsync<Post>(post); // returns Promise<Post> if validation success, throws error if validation fail 2validator.validateOrThrow(post); // performs validation and throws ValidationError if validation fail 3validator.sanitizeAsync<Post>(post);// returns Promise<Post> after sanitization 4validator.sanitizeAndValidate(post); // performs both sanitization and validation of the given object 5validator.sanitizeAndValidateAsync<Post>(post); // performs both sanitization and validation and returns Promise<Post> 6validator.isValid(post); // simply checks if given object is valid. Returns true if it is, false otherwise
You can specify validation message to decorator options and this message will be returned in ValidationError
object returned by validate
method in the case if validation for this field fail.
1import {MinLength, MaxLength} from "validator.ts/decorator/Validation"; 2 3export class Post { 4 5 @MinLength(10, { 6 message: "Title is too short" 7 }) 8 @MaxLength(50, { 9 message: "Title is too long" 10 }) 11 title: string; 12}
If your field is an array and you want to perform validation of each item in the array you need to specify a special decorator option:
1import {MinLength, MaxLength} from "validator.ts/decorator/Validation"; 2 3export class Post { 4 5 @MaxLength(20, { 6 each: true 7 }) 8 tags: string[]; 9}
This will validate each item in post.tags
array.
If your object contains nested objects and you want validator to perform validation of them too, then you need to use special decorator:
1import {ValidateNested} from "validator.ts/decorator/Validation"; 2 3export class Post { 4 5 @ValidateNested() 6 user: User; 7 8}
Sometimes you may want to skip validation of the properties that does not exist in the validating object. This is
usually desirable when you want to update some parts of the document, and want to validate only updated parts,
but skip everything else, e.g. skip missing properties.
In such situations you need to pass a special flag to validate
method:
1import {Validator} from "validator.ts/Validator"; 2// ... 3let validator = new Validator(); 4validator.validate(post, { skipMissingProperties: true });
In different situations you may want to use different validation schemas of the same object. In such cases you can use validation groups.
1import {Validator} from "validator.ts/Validator"; 2import {MinNumber, Length} from "validator.ts/decorator/Validation"; 3 4export class User { 5 6 @MinNumber(12, { 7 groups: ['registration'] 8 }) 9 age: number; 10 11 @Length(2, 20, { 12 groups: ['registration', 'admin'] 13 }) 14 name: string; 15} 16 17let user = new User(); 18user.age = 10; 19user.name = 'Alex'; 20 21let validator = new Validator(); 22 23validator.validate(user, { 24 groups: ['registration'] 25}); // this will not pass validation 26 27validator.validate(user, { 28 groups: ['admin'] 29}); // this will pass validation 30 31validator.validate(user, { 32 groups: ['registration', 'admin'] 33}); // this will not pass validation 34 35validator.validate(user, { 36 groups: [] 37}); // this will pass validation
If you have custom validation logic you want to use as annotations you can do it this way:
First create a file, lets say CustomTextLength.ts
, and create there a new class:
1import {ValidatorInterface} from "validator.ts/ValidatorInterface"; 2import {ValidatorConstraint} from "validator.ts/decorator/Validation"; 3 4@ValidatorConstraint() 5export class CustomTextLength implements ValidatorInterface { 6 7 validate(text: string): boolean { 8 return text.length > 1 && text.length < 10; 9 } 10 11}
Your class should implement ValidatorInterface
interface and its validate
method, which defines logic for data if
its valid or not.
Then you can use your new validation constraint in your class:
1import {Validate} from "validator.ts/decorator/Validation"; 2import {CustomTextLength} from "./CustomTextLength"; 3 4export class Post { 5 6 @Validate(CustomTextLength, { 7 message: "Wrong post title" 8 }) 9 title: string; 10 11}
Here we set our newly created CustomTextLength
validation constraint for Post.title
.
Now you can use validator as usual:
1import {Validator} from "validator.ts/Validator"; 2 3let validator = new Validator(); 4validator.validate(post);
Validator supports service container in the case if want to inject dependencies into your custom validator constraint classes. Here is example how to integrate it with typedi:
1import {Container} from "typedi/Container"; 2import {Validator} from "validator.ts/Validator"; 3 4// do this somewhere in the global application level: 5let validator = Container.get<Validator>(Validator); 6validator.container = Container; 7 8// now everywhere you can inject Validator class which will go from the container 9// also you can inject classes using constructor injection into your custom ValidatorConstraints
There are several method exist in the Validator that allows to perform non-decorator based validation:
1import {Validator} from "validator.ts/Validator"; 2 3// Validation methods 4 5validator.contains(str, seed); 6validator.equals(str, comparison); 7validator.isAfter(date, afterDate); 8validator.isAlpha(str); 9validator.isAlphanumeric(str); 10validator.isAscii(str); 11validator.isBase64(str); 12validator.isBefore(date, beforeDate); 13validator.isBoolean(str); 14validator.isBooleanString(str); 15validator.isByteLength(str, min, max); 16validator.isCreditCard(str); 17validator.isCurrency(str, options); 18validator.isDate(str); 19validator.isDecimal(str); 20validator.isDivisibleBy(str, num); 21validator.isEmail(str, options); 22validator.isFQDN(str, options); 23validator.isFloat(str, options); 24validator.isFullWidth(str); 25validator.isHalfWidth(str); 26validator.isVariableWidth(str); 27validator.isHexColor(str); 28validator.isHexadecimal(str); 29validator.isIP(str, version); 30validator.isISBN(str, version); 31validator.isISIN(str); 32validator.isISO8601(str); 33validator.isIn(str, values); 34validator.isInt(str, options); 35validator.isJSON(str); 36validator.isLength(str, min, max); 37validator.isLowercase(str); 38validator.isMobilePhone(str, locale); 39validator.isMongoId(str); 40validator.isMultibyte(str); 41validator.isNull(str); 42validator.isNumeric(str); 43validator.isSurrogatePair(str); 44validator.isURL(str, options); 45validator.isUUID(str, version); 46validator.isUppercase(str); 47validator.matches(str, pattern, modifiers); 48 49// Sanitization methods 50 51validator.blacklist(str, chars); 52validator.escape(str); 53validator.ltrim(str, chars); 54validator.normalizeEmail(str, isLowercase); 55validator.rtrim(str, chars); 56validator.stripLow(str, keepNewLines); 57validator.toBoolean(input, isStrict); 58validator.toDate(input); 59validator.toFloat(input); 60validator.toInt(input, radix); 61validator.toString(input); 62validator.trim(str, chars); 63validator.whitelist(str, chars); 64
Decorator | Description |
---|---|
@Contains(seed: string) | Checks if the string contains the seed. |
@Equals(comparison: string) | Checks if the string matches the comparison. |
@IsAfter(date: Date) | Checks if the string is a date that's after the specified date. |
@IsAlpha() | Checks if the string contains only letters (a-zA-Z). |
@IsAlphanumeric() | Checks if the string contains only letters and numbers. |
@IsAscii() | Checks if the string contains ASCII chars only. |
@IsBase64() | Checks if a string is base64 encoded. |
@IsBefore(date: Date) | Checks if the string is a date that's before the specified date. |
@IsBoolean() | Checks if a value is a boolean. |
@IsBooleanString() | Checks if a string is a boolean (e.g. is "true" or "false"). |
@IsByteLength(min: number, max?: number) | Checks if the string's length (in bytes) falls in a range. |
@IsCreditCard() | Checks if the string is a credit card. |
@IsCurrency(options?: IsCurrencyOptions) | Checks if the string is a valid currency amount. |
@IsDate() | Checks if the string is a date. |
@IsDecimal() | Checks if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc. |
@IsDivisibleBy(number: number) | Checks if the string is a number that's divisible by another. |
@IsEmail(options?: IsEmailOptions) | Checks if the string is an email. |
@IsFQDN(options?: IsFQDNOptions) | Checks if the string is a fully qualified domain name (e.g. domain.com). |
@IsFloat(options?: IsFloatOptions) | Checks if the string is a float. |
@IsFullWidth() | Checks if the string contains any full-width chars. |
@IsHalfWidth() | Checks if the string contains any half-width chars. |
@IsHexColor() | Checks if the string is a hexadecimal color. |
@IsHexadecimal() | Checks if the string is a hexadecimal number. |
@IsIP(version?: number) | Checks if the string is an IP (version 4 or 6). |
@IsISBN(version?: number) | Checks if the string is an ISBN (version 10 or 13). |
@IsISIN() | Checks if the string is an ISIN (stock/security identifier). |
@IsISO8601() | Checks if the string is a valid ISO 8601 date. |
@IsIn(values: any[]) | Checks if the string is in a array of allowed values. |
@IsInt(options?: IsIntOptions) | Checks if the string is an integer. |
@IsJSON() | Checks if the string is valid JSON. |
@IsLength(min: number, max?: number) | Checks if the string's length falls in a range. |
@IsLowercase() | Checks if the string is lowercase. |
@IsMobilePhone(locale: string) | Checks if the string is a mobile phone number. |
@IsMongoId() | Checks if the string is a valid hex-encoded representation of a MongoDB ObjectId. |
@IsMultibyte() | Checks if the string contains one or more multibyte chars. |
@IsNull() | Checks if the string is null. |
@IsNumeric() | Checks if the string is numeric. |
@IsSurrogatePair() | Checks if the string contains any surrogate pairs chars. |
@IsUrl(options?: IsURLOptions) | Checks if the string is a fully qualified domain name (e.g. domain.com). |
@IsUUID(version?: number) | Checks if the string is a UUID (version 3, 4 or 5). |
@IsUppercase() | Checks if the string is uppercase. |
@IsVariableWidth() | Checks if the string contains a mixture of full and half-width chars. |
@Matches(pattern: RegExp, modifiers?: string) | Checks if string matches the pattern. Either matches('foo', /foo/i) or matches('foo', 'foo', 'i'). |
@MinLength(min: number) | Checks if the string's length is not less then given number. |
@MaxLength(max: number) | Checks if the string's length is not more then given number. |
@MinNumber(min: number) | Checks if the given number is not less then given number. |
@MaxNumber(max: number) | Checks if the given number is not more then given number. |
@NotEmpty() | Checks if given value is not empty. |
@NotEmptyArray() | Checks if given array is not empty. |
@MinSize(min: number) | Checks if array's length is as minimal this number. |
@MaxSize(max: number) | Checks if array's length is as maximal this number. |
Decorator | Description |
---|---|
@Blacklist(chars: RegExp) | Remove characters that appear in the blacklist. |
@Escape() | Replace <, >, &, ', " and / with HTML entities. |
@Ltrim() | Trim characters from the left-side of the input. |
@NormalizeEmail() | Canonicalize an email address. |
@Rtrim() | Trim characters from the right-side of the input. |
@StripLow() | Remove characters with a numerical value < 32 and 127, mostly control characters. |
@ToBoolean(isStrict?: boolean) | Convert the input to a boolean. Everything except for '0', 'false' and '' returns true. In strict mode only '1' and 'true' return true. |
@ToDate() | Convert the input to a date, or null if the input is not a date. |
@ToFloat() | Convert the input to a float. |
@ToInt() | Convert the input to an integer, or NaN if the input is not an integer. |
@ToString() | Convert the input to a string. |
@Trim(chars?: string[]) | Trim characters (whitespace by default) from both sides of the input. You can specify chars that should be trimmed. |
@Whitelist(chars: RegExp) | Remove characters that do not appear in the whitelist.* The characters are used in a RegExp and so you will need to escape some chars, e.g. whitelist(input, '\[\]'). |
Take a look on samples in ./sample for more examples of usages.
Which node version is supported?
This module is tested on > node 4.0, so its highly recommended if you install the latest version of node.
If you are using old versions of node, the major dependency (afaik) of this module is on ES6 Promises, which are
supported by some of the old versions of node too. In the case if your node version does not support promises you
can try to npm install es6-shim
module and include it to make promises work in your version of node.
Is this library production-ready?
The library is under active development, and needs better testing and contributions from community. If you want to use it in production its highly recommended to fix library version that you use in your package.json file. Personally I use it in production.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
packaging workflow detected
Details
Reason
branch protection is not maximal on development and all release branches
Details
Reason
1 commit(s) and 7 issue activity found in the last 90 days -- score normalized to 6
Reason
Found 4/7 approved changesets -- score normalized to 5
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
6 existing vulnerabilities detected
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-06-30
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More