Skip to content

Commit

Permalink
docs: update validation
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 committed Jan 18, 2024
1 parent 9f6f3e7 commit 18f0aad
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
22 changes: 19 additions & 3 deletions site/docs/extensions/validate.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,16 +216,32 @@ export class HomeController {



## 非 Web 场景校验
## 通用场景校验

在非 Web 场景下,没有 `@Body` 等 Web 类装饰器的情况下,也可以使用 `@Valid` 装饰器来进行校验。
如果参数不是 DTO,可以使用 `@Valid` 装饰器进行校验,`@Valid` 装饰器可以直接传递一个 Joi 规则。

```typescript
// src/controller/home.ts
import { Controller, Get, Query } from '@midwayjs/core';
import { Valid, RuleType } from '@midwayjs/validate';
import { UserDTO } from './dto/user';

@Controller('/api/user')
export class HomeController {
@get('/')
async getUser(@Valid(RuleType.number().required()) @Query('id') id: number) {
// ...
}
}
```

在非 Web 场景下,没有 `@Body` 等 Web 类装饰器的情况下,也可以使用 `@Valid` 装饰器来进行校验,如果不传参数,也会复用 DTO 规则。

比如在服务中:

```typescript
import { Valid } from '@midwayjs/validate';
import { Provide } from '@midwayjs/core';

import { UserDTO } from './dto/user';

@Provide()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,15 +229,33 @@ export class HomeController {

In general, use the global default configuration.

## Validation for non-web
## General scenario verification

In non-Web scenarios, if there is no web class decorator such as `@Body`, you can also use the `@Valid` decorator for validation.
If the parameter is not a DTO, you can use the `@Valid` decorator for verification. The `@Valid` decorator can directly pass a Joi rule.

```typescript
// src/controller/home.ts
import { Controller, Get, Query } from '@midwayjs/core';
import { Valid, RuleType } from '@midwayjs/validate';
import { UserDTO } from './dto/user';

@Controller('/api/user')
export class HomeController {
@get('/')
async getUser(@Valid(RuleType.number().required()) @Query('id') id: number) {
// ...
}
}
```

In non-Web scenarios, if there are no Web class decorators such as `@Body`, you can also use the `@Valid` decorator for verification. If no parameters are passed, the DTO rules will be reused.

For example in a service:

```typescript
import { Valid } from '@midwayjs/validate';
import { Provide } from '@midwayjs/core';
import { UserDTO } from './dto/user';

@Provide()
export class UserService {
Expand Down

0 comments on commit 18f0aad

Please sign in to comment.