### Install class-validator Source: https://github.com/typestack/class-validator/blob/develop/README.md Install the package via npm. Ensure you are using npm version 6 or higher for proper dependency management. ```shell npm install class-validator --save ``` -------------------------------- ### Validate Specialized String Formats Source: https://github.com/typestack/class-validator/blob/develop/README.md Examples of using advanced format decorators like IsMilitaryTime, IsHash, and IsStrongPassword for data integrity. ```typescript import { IsMilitaryTime, IsHash, IsStrongPassword } from 'class-validator'; export class SecurityConfig { @IsMilitaryTime() startTime: string; @IsHash('sha256') checksum: string; @IsStrongPassword({ minLength: 10, minLowercase: 1, minUppercase: 1 }) newPassword: string; } ``` -------------------------------- ### Manual Validation Functions (TypeScript) Source: https://github.com/typestack/class-validator/blob/develop/README.md Provides examples of using built-in manual validation functions provided by class-validator, such as `isEmpty` and `isBoolean`. These functions can be used directly for validation checks without decorators. ```typescript import { isEmpty, isBoolean } from 'class-validator'; // Example usage: // const value1 = ''; // const value2 = true; // console.log(isEmpty(value1)); // true // console.log(isBoolean(value2)); // true ``` -------------------------------- ### Use Custom Validator with Arguments (TypeScript) Source: https://github.com/typestack/class-validator/blob/develop/README.md This example illustrates how to pass arguments to a custom validator using the `@Validate` decorator. The arguments are then accessible within the `validate` method via the `validationArguments.constraints` property, allowing for more dynamic validation rules. ```typescript import { Validate } from 'class-validator'; import { CustomTextLength } from './CustomTextLength'; export class Post { @Validate(CustomTextLength, [3, 20], { message: 'Wrong post title', }) title: string; } ``` -------------------------------- ### Validate String Length and Content Source: https://github.com/typestack/class-validator/blob/develop/README.md Demonstrates how to use length-based and pattern-matching decorators to enforce constraints on string properties within a class. ```typescript import { Length, MinLength, MaxLength, Matches } from 'class-validator'; export class UserProfile { @Length(2, 50) username: string; @MinLength(8) password: string; @Matches(/^[a-zA-Z]+$/) name: string; } ``` -------------------------------- ### Configure Validation Behavior with ValidatorOptions Source: https://context7.com/typestack/class-validator/llms.txt Demonstrates how to pass an options object to the validate function to control behavior like skipping missing properties, enabling whitelist mode, and customizing error output structure. ```typescript import { validate, IsString, Length, IsOptional, Allow } from 'class-validator'; class Article { @Length(5, 200) title: string; @IsString() content: string; @IsOptional() @IsString() author?: string; @Allow() metadata: any; } const article = new Article(); article.title = 'Hello'; article.content = 'Article content here'; const errors1 = await validate(article, { skipMissingProperties: true }); const errors2 = await validate(article, { whitelist: true }); const errors3 = await validate(article, { whitelist: true, forbidNonWhitelisted: true }); const errors4 = await validate(article, { stopAtFirstError: true }); const errors5 = await validate(article, { validationError: { target: false, value: false } }); const errors6 = await validate(article, { forbidUnknownValues: true }); ``` -------------------------------- ### Apply Contextual Validation with Groups Source: https://context7.com/typestack/class-validator/llms.txt Shows how to use validation groups to apply different sets of rules depending on the operation context, such as 'create', 'update', or 'admin' actions. ```typescript import { validate, Length, IsEmail, IsOptional, Min } from 'class-validator'; class UserProfile { @Length(3, 50, { groups: ['create', 'update'] }) username: string; @IsEmail({}, { groups: ['create'], message: 'Email required for registration' }) @IsOptional({ groups: ['update'] }) email: string; @Length(8, 100, { groups: ['create'] }) @IsOptional({ groups: ['update'] }) password: string; @Min(0, { groups: ['admin'] }) adminLevel: number; } const newUser = new UserProfile(); newUser.username = 'johndoe'; newUser.email = 'john@example.com'; newUser.password = 'securepass123'; const createErrors = await validate(newUser, { groups: ['create'] }); ``` -------------------------------- ### Create Custom 'IsLongerThan' Validation Decorator (TypeScript) Source: https://github.com/typestack/class-validator/blob/develop/README.md Defines a custom decorator `@IsLongerThan` that validates if a string property's length is greater than another specified string property's length. It uses `registerDecorator` from `class-validator` and includes an example of its usage. ```typescript import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator'; export function IsLongerThan(property: string, validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ name: 'isLongerThan', target: object.constructor, propertyName: propertyName, constraints: [property], options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { const [relatedPropertyName] = args.constraints; const relatedValue = (args.object as any)[relatedPropertyName]; return typeof value === 'string' && typeof relatedValue === 'string' && value.length > relatedValue.length; }, }, }); }; } ``` ```typescript import { IsLongerThan } from './IsLongerThan'; export class Post { title: string; @IsLongerThan('title', { message: 'Text must be longer than the title', }) text: string; } ``` -------------------------------- ### Enforce String Length and Pattern Constraints Source: https://context7.com/typestack/class-validator/llms.txt Apply length constraints using Length, MinLength, and MaxLength, and enforce complex patterns using the Matches decorator with regular expressions. ```typescript import { validate, Length, MinLength, MaxLength, Matches } from 'class-validator'; class RegistrationForm { @MinLength(3, { message: 'Username must be at least 3 characters' }) @MaxLength(20, { message: 'Username cannot exceed 20 characters' }) username: string; @Length(8, 128, { message: 'Password must be 8-128 characters' }) @Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, { message: 'Password must contain uppercase, lowercase, and number' }) password: string; @MaxLength(500) bio: string; } const form = new RegistrationForm(); form.username = 'john_doe'; form.password = 'SecurePass123'; form.bio = 'Hello, I am a developer.'; const errors = await validate(form); ``` -------------------------------- ### String Property Constraints Source: https://github.com/typestack/class-validator/blob/develop/README.md Decorators for validating string length in bytes and character width properties. ```APIDOC ## String Property Constraints ### Description These decorators validate the physical properties of the string, such as byte length or the presence of full-width/half-width characters. ### Available Decorators - **@IsByteLength(min, max)**: Checks if the string length in bytes falls within the specified range. - **@IsFullWidth()**: Checks if the string contains any full-width characters. - **@IsHalfWidth()**: Checks if the string contains any half-width characters. - **@IsVariableWidth()**: Checks if the string contains a mixture of full and half-width characters. ### Usage Example ```typescript import { IsByteLength } from 'class-validator'; export class ContentDto { @IsByteLength(1, 255) content: string; } ``` ``` -------------------------------- ### Validate Network and Address Formats (Ethereum, BTC, Data URI, Email, FQDN) Source: https://github.com/typestack/class-validator/blob/develop/README.md Ensures strings conform to specific network-related formats such as Ethereum addresses, BTC addresses, Data URIs, email addresses, and fully qualified domain names (FQDN). Note that Ethereum address validation is basic and does not check checksums. ```typescript import { IsEthereumAddress, IsBtcAddress, IsDataURI, IsEmail, IsFQDN } from 'class-validator'; export class NetworkDto { @IsEthereumAddress() ethereumAddress: string; @IsBtcAddress() btcAddress: string; @IsDataURI() dataUri: string; @IsEmail() email: string; @IsFQDN() fqdn: string; } ``` -------------------------------- ### Using Custom Validators in Validation Process Source: https://github.com/typestack/class-validator/blob/develop/README.md Illustrates the standard process of validating an object using class-validator, including custom validators. ```APIDOC ## Using Custom Validators in Validation Process This section demonstrates how to execute the validation process on an object that contains custom validation rules. ### Description Shows the typical flow of using the `validate` function from `class-validator` to check an object against its defined constraints, including custom ones. ### Method N/A (This is a usage example) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Validation Example ```typescript import { validate } from 'class-validator'; import { Post } from './Post'; // Assuming Post class with custom validator is defined async function runValidation() { const post = new Post(); post.title = 'Short'; // This will fail the CustomTextLength validation (length 5, expected between 3 and 20) const errors = await validate(post); if (errors.length > 0) { console.log('Validation failed. Errors: ', errors); // Example error output might look like: // [ // { // "target": { "title": "Short" }, // "property": "title", // "children": [], // "constraints": { "customText": "Wrong post title" }, // or 'Text ($value) is too short or too long!' if no message provided // "value": "Short", // "မိ": "CustomTextLength" // } // ] } else { console.log('Validation succeeded.'); } } runValidation(); ``` **Note:** The `validate` function returns a promise that resolves to an array of `ValidationError` objects. If the array is empty, validation passed. ``` -------------------------------- ### String Format Validation Decorators Source: https://github.com/typestack/class-validator/blob/develop/README.md A collection of decorators used to validate string content against specific formats like Base32, Base58, Base64, IBAN, BIC, and various network addresses. ```APIDOC ## String Validation Decorators ### Description These decorators are used on class properties to ensure the input string conforms to specific standards or formats. ### Available Decorators - **@IsBase32()**: Validates Base32 encoding. - **@IsBase58()**: Validates Base58 encoding. - **@IsBase64(options)**: Validates Base64 encoding. - **@IsIBAN()**: Validates International Bank Account Numbers. - **@IsBIC()**: Validates Bank Identification Codes (SWIFT). - **@IsCreditCard()**: Validates credit card number formats. - **@IsCurrency(options)**: Validates currency amount strings. - **@IsEthereumAddress()**: Validates Ethereum address format. - **@IsBtcAddress()**: Validates Bitcoin address format. - **@IsEmail(options)**: Validates email address format. - **@IsFQDN(options)**: Validates fully qualified domain names. ### Usage Example ```typescript import { IsEmail, IsBase64 } from 'class-validator'; export class UserDto { @IsEmail() email: string; @IsBase64() encodedData: string; } ``` ``` -------------------------------- ### Execute Validation with Custom Constraints (TypeScript) Source: https://github.com/typestack/class-validator/blob/develop/README.md This code snippet demonstrates the standard way to execute validation on an object using the `validate` function from `class-validator`. It shows how the validation process, including custom constraints, is initiated and how the results (errors) are handled asynchronously. ```typescript import { validate } from 'class-validator'; // Assuming 'post' is an instance of the Post class with custom validation validate(post).then(errors => { // Handle validation errors // ... }); ``` -------------------------------- ### Implement Validation Groups Source: https://github.com/typestack/class-validator/blob/develop/README.md Shows how to apply different validation schemas to the same object using groups. Validation will only run for decorators matching the provided group names, unless the always: true flag is set. ```typescript import { validate, Min, Length } from 'class-validator'; export class User { @Min(12, { groups: ['registration'], }) age: number; @Length(2, 20, { groups: ['registration', 'admin'], }) name: string; } let user = new User(); user.age = 10; user.name = 'Alex'; validate(user, { groups: ['registration'] }); ``` -------------------------------- ### Validate Array Constraints Source: https://github.com/typestack/class-validator/blob/develop/README.md Shows how to apply array-specific decorators to ensure collections meet size requirements or contain specific elements. ```typescript import { ArrayNotEmpty, ArrayMinSize, ArrayContains } from 'class-validator'; export class TagList { @ArrayNotEmpty() @ArrayMinSize(1) tags: string[]; @ArrayContains(['active']) statusFlags: string[]; } ``` -------------------------------- ### String Content Validation Source: https://github.com/typestack/class-validator/blob/develop/README.md Decorators for validating string content, including multibyte characters, surrogate pairs, uppercase, and URLs. ```APIDOC ## @IsMultibyte() ### Description Checks if the string contains one or more multibyte chars. ### Method N/A (Decorator) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## @IsSurrogatePair() ### Description Checks if the string contains any surrogate pairs chars. ### Method N/A (Decorator) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## @IsUppercase() ### Description Checks if the string is uppercase. ### Method N/A (Decorator) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## @IsUrl(options?: IsURLOptions) ### Description Checks if the string is a URL. ### Method N/A (Decorator) ### Endpoint N/A ### Parameters - **options** (IsURLOptions) - Optional - Configuration options for URL validation. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Defining and Validating a Class Model Source: https://github.com/typestack/class-validator/blob/develop/docs/basics/validating-objects.md This snippet shows how to decorate class properties with validation constraints and trigger validation checks. It covers both promise-based validation and the async/await pattern for error handling. ```typescript import { validate, validateOrReject, IsString, IsInt, IsDate, MaxLength, Min, Max, ValidationError } from 'class-validator'; export class Book { @IsString() @MaxLength(255) title: string; @IsString() @MaxLength(255) author: string; @IsInt() @Min(0) @Max(10) rating: number; @IsDate() publishDate: Date; } const book = new Book(); book.title = 'Don Quixote'; book.author = 'Miguel De Cervantes'; book.rating = 11; book.publishDate = new Date(); validate(book).then((errors: ValidationError[]) => { if (errors.length > 0) { console.warn('validate() - Validation failed. Errors: ', errors); } }); validateOrReject(book).catch((errors: ValidationError[]) => { console.warn('validateOrReject() - Validation failed. Errors: ', errors); }); async function awaitExample() { try { await validateOrReject(book); } catch (errors) { console.warn('Async validateOrReject() - Validation failed. Errors: ', errors); } } ``` -------------------------------- ### Whitelisting and Stripping Properties Source: https://github.com/typestack/class-validator/blob/develop/README.md Configure validation to strip properties not defined by decorators using the whitelist flag. Use @Allow to explicitly permit properties, or forbidNonWhitelisted to throw errors on unknown fields. ```typescript import { validate, Allow } from 'class-validator'; validate(post, { whitelist: true, forbidNonWhitelisted: true }); export class Post { @Allow() title: string; @Min(0) views: number; } ``` -------------------------------- ### Create Custom Validation Decorators with class-validator Source: https://context7.com/typestack/class-validator/llms.txt Demonstrates how to create reusable custom validation decorators like IsLongerThan and IsAfterDate using the registerDecorator function. These decorators allow for complex validation rules to be applied declaratively to class properties. They require class-validator and its associated types for implementation. ```typescript import { registerDecorator, ValidationOptions, ValidationArguments, validate } from 'class-validator'; function IsLongerThan(property: string, validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ name: 'isLongerThan', target: object.constructor, propertyName: propertyName, constraints: [property], options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { const [relatedPropertyName] = args.constraints; const relatedValue = (args.object as any)[relatedPropertyName]; return typeof value === 'string' && typeof relatedValue === 'string' && value.length > relatedValue.length; }, defaultMessage(args: ValidationArguments) { const [relatedPropertyName] = args.constraints; return `${args.property} must be longer than ${relatedPropertyName}`; } } }); }; } function IsAfterDate(property: string, validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ name: 'isAfterDate', target: object.constructor, propertyName: propertyName, constraints: [property], options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { const [relatedPropertyName] = args.constraints; const relatedValue = (args.object as any)[relatedPropertyName]; return value instanceof Date && relatedValue instanceof Date && value > relatedValue; } } }); }; } class Event { title: string; @IsLongerThan('title', { message: 'Description must be longer than title' }) description: string; startDate: Date; @IsAfterDate('startDate', { message: 'End date must be after start date' }) endDate: Date; } const event = new Event(); event.title = 'Conference'; event.description = 'Annual developer conference with workshops and talks'; event.startDate = new Date('2024-06-01'); event.endDate = new Date('2024-06-03'); const errors = await validate(event); console.log('Custom decorators validation:', errors.length === 0); // true ``` -------------------------------- ### String Validation Decorators Source: https://github.com/typestack/class-validator/blob/develop/README.md Decorators for validating string content, length, and specific formats like MIME types, SemVer, or Hashes. ```APIDOC ## String Validation Decorators ### Description These decorators validate string properties based on length, pattern matching, or specific format standards. ### Available Decorators - **@Length(min, max?)**: Checks if string length is within range. - **@MinLength(min)**: Checks if string length is at least min. - **@MaxLength(max)**: Checks if string length is at most max. - **@Matches(pattern, modifiers?)**: Validates string against a RegExp. - **@IsMilitaryTime()**: Validates HH:MM format. - **@IsTimeZone()**: Validates IANA time-zone string. - **@IsHash(algorithm)**: Validates string against hash algorithms (md5, sha256, etc.). - **@IsMimeType()**: Validates MIME type format. - **@IsSemVer()**: Validates Semantic Versioning. - **@IsISSN(options?)**: Validates ISSN format. - **@IsISRC()**: Validates ISRC format. - **@IsRFC3339()**: Validates RFC 3339 date format. - **@IsStrongPassword(options?)**: Validates password strength. ``` -------------------------------- ### Implement Conditional Validation with ValidateIf Source: https://context7.com/typestack/class-validator/llms.txt Demonstrates how to use the @ValidateIf decorator and the validateIf option to conditionally apply validation rules based on the state of other object properties. ```typescript import { validate, ValidateIf, IsNotEmpty, IsEmail, IsUrl, Min } from 'class-validator'; class NotificationSettings { @IsNotEmpty() type: 'email' | 'sms' | 'webhook'; @ValidateIf(o => o.type === 'email') @IsEmail() emailAddress: string; @ValidateIf(o => o.type === 'sms') @IsNotEmpty() phoneNumber: string; @ValidateIf(o => o.type === 'webhook') @IsUrl() webhookUrl: string; @Min(1, { validateIf: (obj, value) => obj.type === 'email' }) @Min(5, { validateIf: (obj, value) => obj.type === 'sms' }) retryCount: number; } const emailNotif = new NotificationSettings(); emailNotif.type = 'email'; emailNotif.emailAddress = 'user@example.com'; emailNotif.retryCount = 3; const emailErrors = await validate(emailNotif); ``` -------------------------------- ### Object and String Case Validation Decorators Source: https://github.com/typestack/class-validator/blob/develop/README.md Decorators for validating object types and string casing. ```APIDOC ## Object and String Case Validation Decorators This section covers decorators for validating object properties and string casing. ### `@IsObject()` - **Description**: Checks if the value is a valid Object. Note that `null`, functions, and arrays will return `false`. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsNotEmptyObject()` - **Description**: Checks if the object is not empty. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsLowercase()` - **Description**: Checks if the string is lowercase. - **Method**: N/A (Decorator) - **Endpoint**: N/A ``` -------------------------------- ### Applying a Custom Validation Constraint Source: https://github.com/typestack/class-validator/blob/develop/README.md Demonstrates how to use the `@Validate` decorator to apply a custom validation constraint to a class property. ```APIDOC ## Applying a Custom Validation Constraint This section explains how to integrate a custom validation constraint into your data models using the `@Validate` decorator. ### Description Applies a previously defined custom validation constraint to a specific property of a class. ### Method N/A (This is a class definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Applying Custom Validator ```typescript import { Validate } from 'class-validator'; import { CustomTextLength } from './CustomTextLength'; // Assuming CustomTextLength is in a separate file export class Post { @Validate(CustomTextLength, { message: 'Title is too short or long!', // Custom error message for this specific field }) title: string; } ``` **Explanation:** - `@Validate(CustomTextLength, ...)` decorator links the `Post.title` property with the `CustomTextLength` validation logic. - The second argument to `@Validate` is an options object, where `message` can be used to override the default error message. ``` -------------------------------- ### Create Custom Validators with ValidatorConstraint Source: https://context7.com/typestack/class-validator/llms.txt Explains how to define custom validation logic by implementing the ValidatorConstraintInterface and applying it to class properties using the @Validate decorator. ```typescript import { validate, ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, Validate } from 'class-validator'; @ValidatorConstraint({ name: 'customTextLength', async: false }) class CustomTextLength implements ValidatorConstraintInterface { validate(text: string, args: ValidationArguments): boolean { const [min, max] = args.constraints; return text.length >= min && text.length <= max; } defaultMessage(args: ValidationArguments): string { const [min, max] = args.constraints; return `Text must be between ${min} and ${max} characters`; } } class BlogPost { @Validate(CustomTextLength, [5, 100], { message: 'Title must be between 5 and 100 characters' }) title: string; } const post = new BlogPost(); post.title = 'My First Blog Post'; const errors = await validate(post); ``` -------------------------------- ### Number Validation with Class-Validator Decorators Source: https://context7.com/typestack/class-validator/llms.txt Demonstrates using decorators like IsNumber, Min, Max, IsInt, and IsPositive to validate numeric properties. Ensures values are within specified ranges, are integers, and are positive. Useful for validating financial amounts, quantities, or other numerical data. ```typescript import { validate, IsNumber, IsInt, Min, Max, IsPositive, IsNegative, IsDivisibleBy } from 'class-validator'; class Transaction { @IsNumber({ maxDecimalPlaces: 2 }) @Min(0.01, { message: 'Amount must be at least $0.01' }) @Max(1000000, { message: 'Amount cannot exceed $1,000,000' }) amount: number; @IsInt({ message: 'Quantity must be a whole number' }) @IsPositive({ message: 'Quantity must be positive' }) quantity: number; @IsDivisibleBy(5, { message: 'Discount must be divisible by 5' }) discountPercent: number; } const transaction = new Transaction(); transaction.amount = 99.99; transaction.quantity = 10; transaction.discountPercent = 15; const errors = await validate(transaction); if (errors.length === 0) { console.log('Transaction is valid'); } ``` -------------------------------- ### Format Validation Decorators Source: https://github.com/typestack/class-validator/blob/develop/README.md Decorators for validating specific string formats like RGB colors, identity cards, passport numbers, postal codes, hexadecimal, octal, MAC addresses, IP addresses, ports, ISBN, EAN, ISIN, ISO8601, JSON, and JWT. ```APIDOC ## Format Validation Decorators This section covers decorators for validating various string formats. ### `@IsRgbColor(options?: IsRgbOptions)` - **Description**: Checks if the string is a valid RGB or RGBA color. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsIdentityCard(locale?: string)` - **Description**: Checks if the string is a valid identity card code for a given locale. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsPassportNumber(countryCode?: string)` - **Description**: Checks if the string is a valid passport number for a specific country code. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsPostalCode(locale?: string)` - **Description**: Checks if the string is a valid postal code for a given locale. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsHexadecimal()` - **Description**: Checks if the string is a valid hexadecimal number. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsOctal()` - **Description**: Checks if the string is a valid octal number. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsMACAddress(options?: IsMACAddressOptions)` - **Description**: Checks if the string is a valid MAC Address. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsIP(version?: "4"|"6")` - **Description**: Checks if the string is a valid IP address (version 4 or 6). - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsPort()` - **Description**: Checks if the string is a valid port number. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsISBN(version?: "10"|"13")` - **Description**: Checks if the string is a valid ISBN (version 10 or 13). - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsEAN()` - **Description**: Checks if the string is a valid EAN (European Article Number). - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsISIN()` - **Description**: Checks if the string is a valid ISIN (stock/security identifier). - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsISO8601(options?: IsISO8601Options)` - **Description**: Checks if the string is a valid ISO 8601 date format. Use `strict = true` for additional date validity checks. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsJSON()` - **Description**: Checks if the string is valid JSON. - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsJWT()` - **Description**: Checks if the string is a valid JWT (JSON Web Token). - **Method**: N/A (Decorator) - **Endpoint**: N/A ### `@IsLatLong()` - **Description**: Checks if the string is a valid latitude-longitude coordinate in the format "lat,long". - **Method**: N/A (Decorator) - **Endpoint**: N/A ``` -------------------------------- ### Common Validation Decorators Source: https://github.com/typestack/class-validator/blob/develop/README.md Decorators for general validation logic, such as checking for defined values, optional properties, equality, and inclusion in sets. ```APIDOC ## Common Validation Decorators ### Description Decorators for general validation logic, such as checking for defined values, optional properties, equality, and inclusion in sets. ### Decorators - **@IsDefined(value: any)** - Description: Checks if value is defined (!== undefined, !== null). This is the only decorator that ignores skipMissingProperties option. - **@IsOptional()** - Description: Checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property. - **@Equals(comparison: any)** - Description: Checks if value equals ("===") comparison. - **@NotEquals(comparison: any)** - Description: Checks if value not equal ("!=") comparison. - **@IsEmpty()** - Description: Checks if given value is empty (=== '', === null, === undefined). - **@IsNotEmpty()** - Description: Checks if given value is not empty (!== '', !== null, !== undefined). - **@IsIn(values: any[])** - Description: Checks if value is in an array of allowed values. - **@IsNotIn(values: any[])** - Description: Checks if value is not in an array of disallowed values. ``` -------------------------------- ### Dynamic Validation Messages with Message Functions Source: https://github.com/typestack/class-validator/blob/develop/README.md Demonstrates how to use a function to generate validation messages dynamically. This approach, using `ValidationArguments`, allows for more complex and context-aware error messages based on the validation context and value. ```typescript import { MinLength, MaxLength, ValidationArguments } from 'class-validator'; export class Post { @MinLength(10, { message: (args: ValidationArguments) => { if (args.value.length === 1) { return 'Too short, minimum length is 1 character'; } else { return 'Too short, minimum length is ' + args.constraints[0] + ' characters'; } }, }) title: string; } ``` -------------------------------- ### String Validation Decorators Source: https://github.com/typestack/class-validator/blob/develop/README.md Decorators for validating string content. ```APIDOC ## Contains ### Description Checks if the string contains the seed. ### Method N/A (Decorator) ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **seed** (string) - Required - The substring to search for. ### Request Example ```typescript import { Contains } from 'class-validator'; class MyClass { @Contains('world') text: string; } ``` ### Response #### Success Response (200) N/A (Decorator) #### Response Example N/A (Decorator) ``` ```APIDOC ## NotContains ### Description Checks if the string not contains the seed. ### Method N/A (Decorator) ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **seed** (string) - Required - The substring to check for absence. ### Request Example ```typescript import { NotContains } from 'class-validator'; class MyClass { @NotContains('spam') message: string; } ``` ### Response #### Success Response (200) N/A (Decorator) #### Response Example N/A (Decorator) ``` ```APIDOC ## IsAlpha ### Description Checks if the string contains only letters (a-zA-Z). ### Method N/A (Decorator) ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { IsAlpha } from 'class-validator'; class MyClass { @IsAlpha() name: string; } ``` ### Response #### Success Response (200) N/A (Decorator) #### Response Example N/A (Decorator) ``` ```APIDOC ## IsAlphanumeric ### Description Checks if the string contains only letters and numbers. ### Method N/A (Decorator) ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { IsAlphanumeric } from 'class-validator'; class MyClass { @IsAlphanumeric() code: string; } ``` ### Response #### Success Response (200) N/A (Decorator) #### Response Example N/A (Decorator) ``` ```APIDOC ## IsDecimal ### Description Checks if the string is a valid decimal value. Default IsDecimalOptions are `force_decimal=False`, `decimal_digits: '1,'`, `locale: 'en-US'`. ### Method N/A (Decorator) ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (IsDecimalOptions) - Optional - Options for decimal validation. ### Request Example ```typescript import { IsDecimal } from 'class-validator'; class MyClass { @IsDecimal({ decimal_digits: '2' }) price: string; } ``` ### Response #### Success Response (200) N/A (Decorator) #### Response Example N/A (Decorator) ``` ```APIDOC ## IsAscii ### Description Checks if the string contains ASCII chars only. ### Method N/A (Decorator) ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { IsAscii } from 'class-validator'; class MyClass { @IsAscii() asciiString: string; } ``` ### Response #### Success Response (200) N/A (Decorator) #### Response Example N/A (Decorator) ``` -------------------------------- ### Passing Constraints to Custom Validators Source: https://github.com/typestack/class-validator/blob/develop/README.md Shows how to pass additional constraints to a custom validator and access them within the validation logic. ```APIDOC ## Passing Constraints to Custom Validators This section covers how to pass dynamic constraints to your custom validators and utilize them during the validation process. ### Description Allows passing arguments (constraints) to a custom validator, making it more flexible and reusable. ### Method N/A (This is a class definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Example with Constraints **1. Applying the validator with constraints:** ```typescript import { Validate } from 'class-validator'; import { CustomTextLength } from './CustomTextLength'; export class Post { @Validate(CustomTextLength, [3, 20], { // [3, 20] are the constraints passed message: 'Wrong post title', }) title: string; } ``` **2. Accessing constraints within the validator:** ```typescript import { ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator'; @ValidatorConstraint() export class CustomTextLength implements ValidatorConstraintInterface { validate(text: string, validationArguments: ValidationArguments) { const minLength = validationArguments.constraints[0]; // Accessing the first constraint (3) const maxLength = validationArguments.constraints[1]; // Accessing the second constraint (20) return text.length >= minLength && text.length <= maxLength; } // defaultMessage can also be defined here if needed } ``` **Explanation:** - The second argument to `@Validate` (e.g., `[3, 20]`) is an array of constraints passed to the validator. - Inside the `validate` method, `validationArguments.constraints` is an array containing these passed values, which can be accessed by index. ``` -------------------------------- ### Validate String Character Width (Fullwidth, Halfwidth, Variablewidth) Source: https://github.com/typestack/class-validator/blob/develop/README.md Checks the character width properties of a string. IsFullWidth checks for full-width characters, IsHalfWidth for half-width, and IsVariableWidth verifies a mix of both. ```typescript import { IsFullWidth, IsHalfWidth, IsVariableWidth } from 'class-validator'; export class WidthDto { @IsFullWidth() fullWidthString: string; @IsHalfWidth() halfWidthString: string; @IsVariableWidth() variableWidthString: string; } ``` -------------------------------- ### Date Validation Decorators Source: https://github.com/typestack/class-validator/blob/develop/README.md Decorators for validating date values. ```APIDOC ## MinDate ### Description Checks if the value is a date that's after the specified date. ### Method N/A (Decorator) ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **date** (Date | (() => Date)) - Required - The minimum allowed date. ### Request Example ```typescript import { MinDate } from 'class-validator'; class MyClass { @MinDate(new Date(2023, 0, 1)) startDate: Date; } ``` ### Response #### Success Response (200) N/A (Decorator) #### Response Example N/A (Decorator) ``` ```APIDOC ## MaxDate ### Description Checks if the value is a date that's before the specified date. ### Method N/A (Decorator) ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **date** (Date | (() => Date)) - Required - The maximum allowed date. ### Request Example ```typescript import { MaxDate } from 'class-validator'; class MyClass { @MaxDate(new Date(2023, 11, 31)) endDate: Date; } ``` ### Response #### Success Response (200) N/A (Decorator) #### Response Example N/A (Decorator) ``` -------------------------------- ### Validate Common String Formats Source: https://context7.com/typestack/class-validator/llms.txt Utilize decorators like IsEmail, IsUrl, IsFQDN, IsIP, and IsUUID to enforce specific string format constraints on class properties. ```typescript import { validate, IsEmail, IsUrl, IsFQDN, IsIP, IsUUID } from 'class-validator'; class ContactInfo { @IsEmail({}, { message: 'Please provide a valid email' }) email: string; @IsUrl({ require_protocol: true, require_tld: true }) website: string; @IsFQDN({}, { message: 'Invalid domain name' }) domain: string; @IsIP('4') ipAddress: string; @IsUUID('4') userId: string; } const contact = new ContactInfo(); contact.email = 'user@example.com'; contact.website = 'https://example.com'; contact.domain = 'api.example.com'; contact.ipAddress = '192.168.1.1'; contact.userId = '550e8400-e29b-41d4-a716-446655440000'; const errors = await validate(contact); console.log('Validation passed:', errors.length === 0); ``` -------------------------------- ### Creating a Custom Validation Constraint Source: https://github.com/typestack/class-validator/blob/develop/README.md This snippet shows how to define a custom validation class that implements ValidatorConstraintInterface. ```APIDOC ## Creating a Custom Validation Constraint This section details how to create a custom validation class using `@ValidatorConstraint` and `ValidatorConstraintInterface`. ### Description Defines a custom validation logic that can be reused across different classes. ### Method N/A (This is a class definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Custom Validation Class Example ```typescript import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator'; @ValidatorConstraint({ name: 'customText', async: false }) export class CustomTextLength implements ValidatorConstraintInterface { validate(text: string, args: ValidationArguments) { // Basic validation logic: text length between 2 and 9 characters return text.length > 1 && text.length < 10; } defaultMessage(args: ValidationArguments) { // Default error message if validation fails return 'Text ($value) is too short or too long!'; } } ``` **Notes:** - The `name` property in `@ValidatorConstraint` is optional and used as the error type. - The `validate` method contains the core validation logic and should return a boolean or a Promise for async operations. - The `defaultMessage` method provides a fallback error message. ``` -------------------------------- ### Phone Number and Locale Validation Source: https://github.com/typestack/class-validator/blob/develop/README.md Decorators for validating mobile phone numbers, general phone numbers, and locale formats. ```APIDOC ## @IsMobilePhone(locale: string) ### Description Checks if the string is a mobile phone number. ### Method N/A (Decorator) ### Endpoint N/A ### Parameters - **locale** (string) - Optional - The locale to use for validation (e.g., 'en-US'). ### Request Example N/A ### Response N/A ``` ```APIDOC ## @IsPhoneNumber(region: string) ### Description Checks if the string is a valid phone number using libphonenumber-js. ### Method N/A (Decorator) ### Endpoint N/A ### Parameters - **region** (string) - Optional - The region code (e.g., 'US') to use for validation. ### Request Example N/A ### Response N/A ``` ```APIDOC ## @IsLocale() ### Description Checks if the string is a locale. ### Method N/A (Decorator) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response N/A ``` -------------------------------- ### Type Validation with Class-Validator Decorators Source: https://context7.com/typestack/class-validator/llms.txt Illustrates type checking decorators such as IsBoolean, IsDate, IsString, IsArray, IsEnum, and IsObject. These decorators verify that property values match expected JavaScript types or specific enum values. Essential for ensuring data conforms to predefined types. ```typescript import { validate, IsBoolean, IsDate, IsString, IsArray, IsEnum, IsObject } from 'class-validator'; enum Status { PENDING = 'pending', ACTIVE = 'active', COMPLETED = 'completed' } class Task { @IsString() title: string; @IsBoolean() isCompleted: boolean; @IsDate() dueDate: Date; @IsEnum(Status, { message: 'Status must be pending, active, or completed' }) status: Status; @IsArray() @IsString({ each: true }) // Validate each array item is a string tags: string[]; @IsObject() metadata: object; } const task = new Task(); task.title = 'Complete project'; task.isCompleted = false; task.dueDate = new Date('2024-12-31'); task.status = Status.PENDING; task.tags = ['urgent', 'work']; task.metadata = { priority: 'high' }; const errors = await validate(task); ``` -------------------------------- ### Create Custom 'IsUserAlreadyExist' Async Validation Decorator (TypeScript) Source: https://github.com/typestack/class-validator/blob/develop/README.md Implements an asynchronous custom decorator `@IsUserAlreadyExist` to check if a username already exists in the repository. It utilizes `ValidatorConstraint` with `async: true` and demonstrates its application in a User class. ```typescript import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, } from 'class-validator'; @ValidatorConstraint({ async: true }) export class IsUserAlreadyExistConstraint implements ValidatorConstraintInterface { validate(userName: any, args: ValidationArguments) { return UserRepository.findOneByName(userName).then(user => { if (user) return false; return true; }); } } export function IsUserAlreadyExist(validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ target: object.constructor, propertyName: propertyName, options: validationOptions, constraints: [], validator: IsUserAlreadyExistConstraint, }); }; } ``` ```typescript import { IsUserAlreadyExist } from './IsUserAlreadyExist'; export class User { @IsUserAlreadyExist({ message: 'User $value already exists. Choose another name.', }) name: string; } ``` -------------------------------- ### Validating Set Elements with `each: true` Source: https://github.com/typestack/class-validator/blob/develop/README.md Demonstrates how to validate each element within a `Set` property by using the `each: true` decorator option. This is useful for ensuring all unique values in a set conform to specific validation rules. ```typescript import { MinLength, MaxLength } from 'class-validator'; export class Post { @MaxLength(20, { each: true, }) tags: Set; } ```