Skip to content

Commit e9a397f

Browse files
authored
feat: add Contains decorator (#210)
1 parent 32138ce commit e9a397f

11 files changed

Lines changed: 195 additions & 71 deletions

File tree

README.ko.md

Lines changed: 36 additions & 35 deletions
Large diffs are not rendered by default.

README.md

Lines changed: 37 additions & 36 deletions
Large diffs are not rendered by default.

apps/docs/docs/decorators/validators.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ Validates that a number is within the specified range, inclusive of the minimum
2929
- **`min`**: The minimum allowed value.
3030
- **`max`**: The maximum allowed value.
3131

32+
### `@Contains(seed: string)`
33+
34+
Validates that the string contains the specified substring.
35+
36+
- **`seed`**: The substring that must be present in the string.
37+
- **`message`** (optional): The error message to display when validation fails. If omitted, a default message will be used.
38+
3239
### `@Prefix(value: string)`
3340

3441
Validates that a string starts with the specified prefix.

apps/docs/i18n/de/docusaurus-plugin-content-docs/current/decorators/validators.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ Validiert, dass eine Zahl innerhalb des angegebenen Bereichs liegt, einschließl
2929
- **`min`**: Der zulässige Mindestwert.
3030
- **`max`**: Der zulässige Höchstwert.
3131

32+
### `@Contains(seed: string)`
33+
34+
Validiert, dass ein String den angegebenen Teilstring enthält.
35+
36+
- **`seed`**: Der Teilstring, der im String enthalten sein muss.
37+
- **`message`** (optional): Die Fehlermeldung, die bei fehlgeschlagener Validierung angezeigt wird. Wenn nicht angegeben, wird eine Standardmeldung verwendet.
38+
3239
### `@Prefix(value: string)`
3340

3441
Validiert, dass ein String mit dem angegebenen Präfix beginnt.

apps/docs/i18n/fr/docusaurus-plugin-content-docs/current/decorators/validators.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ Valide qu'un nombre est dans la plage spécifiée, inclusivement des valeurs min
2929
- **`min`** : La valeur minimale autorisée.
3030
- **`max`** : La valeur maximale autorisée.
3131

32+
### `@Contains(seed: string)`
33+
34+
Valide qu'une chaîne contient la sous-chaîne spécifiée.
35+
36+
- **`seed`** : La sous-chaîne qui doit être présente dans la chaîne.
37+
- **`message`** (optionnel) : Le message d'erreur à afficher en cas d'échec de la validation. Si omis, un message par défaut sera utilisé.
38+
3239
### `@Prefix(value: string)`
3340

3441
Valide qu'une chaîne commence par le préfixe spécifié.

apps/docs/i18n/ko/docusaurus-plugin-content-docs/current/decorators/validators.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,15 @@ title: 유효성 검사 데코레이터
4343

4444
---
4545

46+
### `@Contains(seed: string)`
47+
48+
문자열이 지정된 부분 문자열을 포함하는지 검증합니다.
49+
50+
* **`seed`**: 문자열에 반드시 포함되어야 하는 부분 문자열
51+
* **`message`** (선택): 검증 실패 시 표시할 오류 메시지. 생략하면 기본 메시지가 사용됩니다.
52+
53+
---
54+
4655
### `@Prefix(value: string)`
4756

4857
문자열이 지정된 접두사로 시작하는지 검증합니다.

apps/docs/i18n/ru/docusaurus-plugin-content-docs/current/decorators/validators.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ Express-Cargo использует декораторы для валидаци
2929
- **`min`**: Минимально допустимое значение.
3030
- **`max`**: Максимально допустимое значение.
3131

32+
### `@Contains(seed: string)`
33+
34+
Проверяет, что строка содержит указанную подстроку.
35+
36+
- **`seed`**: Подстрока, которая должна присутствовать в строке.
37+
- **`message`** (необязательно): Сообщение об ошибке, отображаемое при неудачной валидации. Если не указано, используется сообщение по умолчанию.
38+
3239
### `@Prefix(value: string)`
3340

3441
Проверяет, что строка начинается с указанного префикса.

apps/example/README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,29 @@ curl -X POST 'http://localhost:3000/range' \
362362

363363
---
364364

365+
### @Contains
366+
367+
```typescript
368+
class ContainsExample {
369+
@Body()
370+
@Contains('hello')
371+
greeting!: string
372+
}
373+
374+
router.post('/contains', bindingCargo(ContainsExample), (req, res) => {
375+
const cargo = getCargo<ContainsExample>(req)
376+
res.json(cargo)
377+
})
378+
```
379+
380+
```shell
381+
curl -X POST 'http://localhost:3000/contains' \
382+
-H 'Content-Type: application/json' \
383+
-d '{"greeting": "hello world"}'
384+
```
385+
386+
---
387+
365388
### @Prefix
366389

367390
```typescript

apps/example/src/routers/validator.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
With,
3434
Without,
3535
Enum,
36+
Contains,
3637
ListContains, ListNotContains, ListMaxSize, Type, List, ListMinSize,
3738
} from 'express-cargo'
3839

@@ -121,6 +122,17 @@ router.post('/not-equal', bindingCargo(NotEqualExample), (req, res) => {
121122
res.json(cargo)
122123
})
123124

125+
class ContainsExample {
126+
@Body()
127+
@Contains('hello')
128+
greeting!: string
129+
}
130+
131+
router.post('/contains', bindingCargo(ContainsExample), (req, res) => {
132+
const cargo = getCargo<ContainsExample>(req)
133+
res.json(cargo)
134+
})
135+
124136
class PrefixExample {
125137
@Body()
126138
@Prefix('https://')

packages/express-cargo/src/validator.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,26 @@ export function Max(maximum: number, message?: cargoErrorMessage): TypedProperty
4949
}
5050
}
5151

52+
/**
53+
* Checks if the string contains the specified substring.
54+
* @param seed - The substring to search for.
55+
* @param message - Optional custom error message.
56+
*/
57+
export function Contains(seed: string, message?: cargoErrorMessage): TypedPropertyDecorator<string> {
58+
return (target, propertyKey) => {
59+
addValidator(
60+
target,
61+
propertyKey,
62+
new ValidatorRule(
63+
propertyKey,
64+
'contains',
65+
val => typeof val === 'string' && val.includes(seed),
66+
message || `${String(propertyKey)} must contain ${seed}`,
67+
),
68+
)
69+
}
70+
}
71+
5272
/**
5373
* Checks if the string starts with the specified prefix.
5474
* @param prefixText - The prefix string.

0 commit comments

Comments
 (0)