Skip to content

Commit

Permalink
docs: optimize hertz vd tag description (#995)
Browse files Browse the repository at this point in the history
Co-authored-by: kinggo <lilong.21@bytedance.com>
  • Loading branch information
chaoranz758 and li-jin-gou committed Mar 22, 2024
1 parent d39106c commit ee7bb09
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
Expand Up @@ -74,7 +74,30 @@ If [api-annotations](/docs/hertz/tutorials/toolkit/annotation/#supported-api-ann
| json | This tag is used to bind json parameters in the request body which content-type is `application/json` |
| raw_body | This tag is used to bind the original body (bytes type) of the request, and parameters can be bound even if the bound field name is not specified. (Note: raw_body has the lowest binding priority. When multiple tags are specified, once other tags successfully bind parameters, the body content will not be bound) |
| vd | `vd` short for validator, [The grammar of validation parameter](https://github.com/bytedance/go-tagexpr/tree/master/validator) |
| default | Set default value |
| default | Set default value |

### Parameter Validation

Specific validation syntax can be referred to [The grammar of validation parameter](https://github.com/bytedance/go-tagexpr/tree/master/validator).

When generating code without IDL, directly tag the corresponding structure field, for example:

```go
type InfoRequest struct {
Name string `vd:"$!='your string'"`
}
```

When generating code through IDL, corresponding annotations need to be added, please refer to [field-annotation](/docs/hertz/tutorials/toolkit/annotation/#field-annotation).

Here are common usage examples:

- length validation for string and list `len($)>0`
- regex pattern match for string `regexp('^\\w*$')"`
- value validation for numertic field `$>0`
- validation for pointer field `num==nil || num>0`
- validation for enum types `type=="hello" || type == "world"`
- custom error message `msg:'C must be false when S.A>0'"`

### Parameter binding precedence

Expand Down
Expand Up @@ -76,6 +76,29 @@ func main() {
| vd | 参数校验,[校验语法](https://github.com/bytedance/go-tagexpr/tree/master/validator) |
| default | 设置默认值 |

### 参数校验

具体校验语法可参考[校验语法](https://github.com/bytedance/go-tagexpr/tree/master/validator)

不通过 IDL 生成代码时直接在对应结构体字段打 tag,示例:

```go
type InfoRequest struct {
Name string `vd:"$!='your string'"`
}
```

通过 IDL 生成代码时需添加相应的注解,可参考[Field 注解](/zh/docs/hertz/tutorials/toolkit/annotation/#field-注解)

下面给出常见用法:

- string 和 list 的长度验证 `len($)>0`
- 字符串正则匹配 `regexp('^\\w*$')"`
- 验证数字字段的的值 `$>0`
- 验证指针字段 `num==nil || num>0`
- 验证枚举类型 `type=="hello" || type == "world"`
- 自定义错误信息 `msg:'C must be false when S.A>0'"`

### 参数绑定优先级

```text
Expand Down

0 comments on commit ee7bb09

Please sign in to comment.