Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(onlinedocs): mkdocs with material theme for the readme file to a… #2578

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions class-validator-docs/docs/arrays.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Validating Arrays

## Basic Array Validation

If your field is an array and you want to perform validation of each item in the array, you must specify a special `each: true` decorator option:

```typescript
import { MaxLength } from 'class-validator';

export class Post {
@MaxLength(20, {
each: true,
})
tags: string[];
}
```

## Array-specific Decorators

There are also several decorators specifically for array validation:

| Decorator | Description |
| --------- | ----------- |
| `@ArrayContains(values: any[])` | Checks if array contains all values from the given array of values. |
| `@ArrayNotContains(values: any[])` | Checks if array does not contain any of the given values. |
| `@ArrayNotEmpty()` | Checks if given array is not empty. |
| `@ArrayMinSize(min: number)` | Checks if array's length is greater than or equal to the specified number. |
| `@ArrayMaxSize(max: number)` | Checks if array's length is less or equal to the specified number. |
| `@ArrayUnique()` | Checks if all array's values are unique. |

Example:

```typescript
import { ArrayMinSize, ArrayMaxSize, ArrayUnique } from 'class-validator';

export class Post {
@ArrayMinSize(1)
@ArrayMaxSize(10)
@ArrayUnique()
tags: string[];
}
```
45 changes: 45 additions & 0 deletions class-validator-docs/docs/conditional.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Conditional Validation

The conditional validation decorator (`@ValidateIf`) can be used to ignore the validators on a property when the provided condition function returns false.

## Basic Usage

```typescript
import { ValidateIf, IsNotEmpty } from 'class-validator';

export class Post {
otherProperty: string;

@ValidateIf(o => o.otherProperty === 'value')
@IsNotEmpty()
example: string;
}
```

In this example, the validation rules applied to `example` won't be run unless the object's `otherProperty` is `"value"`.

## Important Notes

1. When the condition is false, all validation decorators are ignored
2. The condition function takes the object being validated as a parameter
3. The condition function must return a boolean
4. Multiple `@ValidateIf` decorators can be used on the same property

## Advanced Example

```typescript
import { ValidateIf, IsNotEmpty, IsString } from 'class-validator';

export class User {
@IsString()
type: string;

@ValidateIf(o => o.type === 'admin')
@IsNotEmpty()
adminKey: string;

@ValidateIf(o => o.type === 'user')
@IsNotEmpty()
userKey: string;
}
```
35 changes: 35 additions & 0 deletions class-validator-docs/docs/context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Passing Context to Decorators

## Overview

It's possible to pass a custom object to decorators which will be accessible on the `ValidationError` instance of the property if validation failed.

## Example

```typescript
import { validate } from 'class-validator';

class MyClass {
@MinLength(32, {
message: 'EIC code must be at least 32 characters',
context: {
errorCode: 1003,
developerNote: 'The validated string must contain 32 or more characters.',
},
})
eicCode: string;
}

const model = new MyClass();

validate(model).then(errors => {
// errors[0].contexts['minLength'].errorCode === 1003
});
```

## Use Cases

1. Adding error codes for API responses
2. Including developer notes in validation errors
3. Providing additional metadata for error handling
4. Customizing error messages based on context
78 changes: 78 additions & 0 deletions class-validator-docs/docs/custom-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Custom Validation

## Custom Validation Classes

### Creating a Custom Validator

```typescript
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ name: 'customText', async: false })
export class CustomTextLength implements ValidatorConstraintInterface {
validate(text: string, args: ValidationArguments) {
return text.length > 1 && text.length < 10;
}

defaultMessage(args: ValidationArguments) {
return 'Text ($value) is too short or too long!';
}
}
```

### Using Custom Validator

```typescript
import { Validate } from 'class-validator';
import { CustomTextLength } from './CustomTextLength';

export class Post {
@Validate(CustomTextLength, {
message: 'Title is too short or long!'
})
title: string;
}
```

## Custom Validation Decorators

### Creating a Custom Decorator

```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;
}
}
});
};
}
```

### Using Custom Decorator

```typescript
import { IsLongerThan } from './IsLongerThan';

export class Post {
title: string;

@IsLongerThan('title', {
message: 'Text must be longer than the title'
})
text: string;
}
```
28 changes: 28 additions & 0 deletions class-validator-docs/docs/decorators.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Validation Decorators

## Common validation decorators

| Decorator | Description |
| --------- | ----------- |
| `@IsDefined(value: any)` | Checks if value is defined (!== undefined, !== null). This is the only decorator that ignores skipMissingProperties option. |
| `@IsOptional()` | Checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property. |
| `@Equals(comparison: any)` | Checks if value equals ("===") comparison. |
| `@NotEquals(comparison: any)` | Checks if value not equal ("!==") comparison. |
| `@IsEmpty()` | Checks if given value is empty (=== '', === null, === undefined). |
| `@IsNotEmpty()` | Checks if given value is not empty (!== '', !== null, !== undefined). |
| `@IsIn(values: any[])` | Checks if value is in an array of allowed values. |
| `@IsNotIn(values: any[])` | Checks if value is not in an array of disallowed values. |

## Type validation decorators

| Decorator | Description |
| --------- | ----------- |
| `@IsBoolean()` | Checks if a value is a boolean. |
| `@IsDate()` | Checks if the value is a date. |
| `@IsString()` | Checks if the value is a string. |
| `@IsNumber(options: IsNumberOptions)` | Checks if the value is a number. |
| `@IsInt()` | Checks if the value is an integer number. |
| `@IsArray()` | Checks if the value is an array |
| `@IsEnum(entity: object)` | Checks if the value is a valid enum |

See the [full list of validation decorators](validation-decorators.md) for more details.
50 changes: 50 additions & 0 deletions class-validator-docs/docs/groups.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Validation Groups

## Overview

In different situations you may want to use different validation schemas for the same object. In such cases you can use validation groups.

## Basic Usage

```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']
}); // this will not pass validation

validate(user, {
groups: ['admin']
}); // this will pass validation

validate(user, {
groups: ['registration', 'admin']
}); // this will not pass validation

validate(user, {
groups: undefined // the default
}); // this will not pass validation
```

## Important Notes

1. The `always: true` flag in validation options means the validation must be applied regardless of groups
2. Multiple groups can be specified for a single decorator
3. If no groups are specified, the default group is used
4. Groups can be used to create different validation scenarios for the same object
60 changes: 60 additions & 0 deletions class-validator-docs/docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Class Validator

![Build Status](https://github.com/typestack/class-validator/workflows/CI/badge.svg)
[![codecov](https://codecov.io/gh/typestack/class-validator/branch/develop/graph/badge.svg)](https://codecov.io/gh/typestack/class-validator)
[![npm version](https://badge.fury.io/js/class-validator.svg)](https://badge.fury.io/js/class-validator)
[![install size](https://packagephobia.now.sh/badge?p=class-validator)](https://packagephobia.now.sh/result?p=class-validator)

Class-validator is a powerful validation library for TypeScript and JavaScript that allows you to use decorator and non-decorator based validation. It uses [validator.js](https://github.com/chriso/validator.js) internally to perform validation and works on both browser and node.js platforms.

## Key Features

- Decorator and non-decorator based validation
- Cross-platform compatibility (browser & node.js)
- Works with TypeScript and JavaScript
- Validates objects against classes
- Validates arrays and nested objects
- Custom validation decorators
- Service container support
- Rich set of built-in validators

## Quick Example

```typescript
import { validate } from 'class-validator';
import { Length, Contains, IsInt, Min, Max, IsEmail } from 'class-validator';

export class Post {
@Length(10, 20)
title: string;

@Contains('hello')
text: string;

@IsInt()
@Min(0)
@Max(10)
rating: number;

@IsEmail()
email: string;
}

let post = new Post();
post.title = 'Hello'; // too short
post.text = 'this is a great post about hell world'; // doesn't contain "hello"
post.rating = 11; // too high
post.email = 'google.com'; // not an email

validate(post).then(errors => {
if (errors.length > 0) {
console.log('validation failed. errors: ', errors);
} else {
console.log('validation succeed');
}
});
```

## Contributing

For information about how to contribute to this project, see [TypeStack's general contribution guide](https://github.com/typestack/.github/blob/master/CONTRIBUTING.md).
Loading