Skip to content

Commit

Permalink
docs: update validate.md (#4156)
Browse files Browse the repository at this point in the history
  • Loading branch information
erweixin authored Jul 16, 2024
1 parent 9bb5357 commit 9001580
Show file tree
Hide file tree
Showing 4 changed files with 295 additions and 1 deletion.
134 changes: 134 additions & 0 deletions docs/guide/advanced/validate.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ At the same time, we can also implement linkage verification in effects or x-rea

Specific rule verification document reference [FieldValidator](https://core.formilyjs.org/api/models/field#fieldvalidator)

Form validation is an important part of optimizing user experience and ensuring data accuracy in forms. Formily provides various validation methods, including built-in rule validation, built-in format validation, and custom rule validation. In the following sections, we will introduce these validation methods one by one.

## Built-in rule check

Built-in rule validation refers to the common validation rules provided by Formily, such as required, max, min, len, enum, const, multipleOf, etc. These rules can be described using JSON Schema properties or the x-validator property. Formily supports multiple ways of writing built-in rules and it is recommended for teams to establish internal conventions based on their usage habits.

#### Markup Schema Use Cases

```tsx
Expand Down Expand Up @@ -1432,6 +1436,136 @@ export default () => (
)
```

## Using Third-Party Validation Libraries

With the powerful validation engine of Formily, it is extremely convenient to adapt to third-party validation libraries such as yup. Here is an example of how to use it:

#### JSON Schema Cases

```tsx
import React from 'react'
import { createForm, registerValidateRules } from '@formily/core'
import { createSchemaField } from '@formily/react'
import { Form, FormItem, Input, NumberPicker } from '@formily/antd'
import { string } from 'yup'

const form = createForm()

const SchemaField = createSchemaField({
components: {
Input,
FormItem,
NumberPicker,
},
})

registerValidateRules({
yup: async (value, rule) => {
try {
await rule.yup().validate(value)
return '' // Return an empty string when validation is successful
} catch (err) {
return err.errors.join(',') // Return the error message when validation fails
}
},
})

const schema = {
type: 'object',
properties: {
global_style_1: {
title: 'Maximum length is 2',
'x-validator': [
{
triggerType: 'onBlur',
yup: () => string().required('required'),
},
{
triggerType: 'onBlur',
yup: () => string().max(2, 'Maximum length is 2'),
},
],
'x-component': 'Input',
'x-decorator': 'FormItem',
},
global_style_2: {
title: 'email',
required: true,
'x-validator': {
triggerType: 'onBlur',
yup: () => string().email(),
},
'x-component': 'Input',
'x-decorator': 'FormItem',
},
},
}

export default () => (
<Form form={form} labelCol={6} wrapperCol={10}>
<SchemaField schema={schema} />
</Form>
)
```

#### Pure JSX Cases

```tsx
import React from 'react'
import { createForm, registerValidateRules } from '@formily/core'
import { Field } from '@formily/react'
import { Form, FormItem, Input, NumberPicker } from '@formily/antd'
import { string, number } from 'yup'

const form = createForm()

registerValidateRules({
yup: async (value, rule) => {
try {
await rule.yup().validate(value)
return '' // Return an empty string when validation is successful
} catch (err) {
return err.errors.join(',') // Return the error message when validation fails
}
},
})

export default () => (
<Form form={form} labelCol={6} wrapperCol={10}>
<Field
name="global_style_1"
title="email"
required
validator={{
yup: () => string().email(),
}}
component={[Input]}
decorator={[FormItem]}
/>
<Field
name="global_style_2"
title="max 30"
required
validator={{
yup: () => number().max(30),
}}
component={[NumberPicker]}
decorator={[FormItem]}
/>
<Field
name="global_style_3"
title="email"
required
validator={{
yup: () => string().email(),
}}
component={[Input]}
decorator={[FormItem]}
/>
</Form>
)
```

## Custom Format Verification

#### Markup Schema Cases
Expand Down
134 changes: 134 additions & 0 deletions docs/guide/advanced/validate.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ Formily 的表单校验使用了极其强大且灵活的@formily/validator 校

具体规则校验文档参考 [FieldValidator](https://core.formilyjs.org/zh-CN/api/models/field#fieldvalidator)

表单校验是表单中优化用户体验和保证数据准确性的重要一环,Formily 提供了多种校验方式,包括内置规则校验、内置格式校验、自定义规则校验等,下面我们将逐一介绍这些校验方式。

## 内置规则校验

内置规则校验是指 Formily 提供的一些常用校验规则,比如必填、最大值、最小值、长度、枚举、常量、整除等,实现了最简单和最通用的校验,这些规则可以通过 JSON Schema 的属性描述,也可以通过 x-validator 属性描述。Formily 支持多种形式的内置规则书写方式,建议团队内部根据使用习惯制定团队规范。

#### Markup Schema 案例

```tsx
Expand Down Expand Up @@ -1432,6 +1436,136 @@ export default () => (
)
```

## 使用第三方校验库

凭借 Formily 极为强大的校验引擎,能够极为便捷地适配诸如 yup 等第三方校验库。其使用示例如下:

#### JSON Schema 案例

```tsx
import React from 'react'
import { createForm, registerValidateRules } from '@formily/core'
import { createSchemaField } from '@formily/react'
import { Form, FormItem, Input, NumberPicker } from '@formily/antd'
import { string } from 'yup'

const form = createForm()

const SchemaField = createSchemaField({
components: {
Input,
FormItem,
NumberPicker,
},
})

registerValidateRules({
yup: async (value, rule) => {
try {
await rule.yup().validate(value)
return '' // 验证成功时返回空字符串
} catch (err) {
return err.errors.join(',') // 验证失败时返回错误信息
}
},
})

const schema = {
type: 'object',
properties: {
global_style_1: {
title: '最大长度为 2',
'x-validator': [
{
triggerType: 'onBlur',
yup: () => string().required('必填'),
},
{
triggerType: 'onBlur',
yup: () => string().max(2, '最大长度为 2'),
},
],
'x-component': 'Input',
'x-decorator': 'FormItem',
},
global_style_2: {
title: 'email',
required: true,
'x-validator': {
triggerType: 'onBlur',
yup: () => string().email(),
},
'x-component': 'Input',
'x-decorator': 'FormItem',
},
},
}

export default () => (
<Form form={form} labelCol={6} wrapperCol={10}>
<SchemaField schema={schema} />
</Form>
)
```

#### 纯 JSX 案例

```tsx
import React from 'react'
import { createForm, registerValidateRules } from '@formily/core'
import { Field } from '@formily/react'
import { Form, FormItem, Input, NumberPicker } from '@formily/antd'
import { string, number } from 'yup'

const form = createForm()

registerValidateRules({
yup: async (value, rule) => {
try {
await rule.yup().validate(value)
return '' // 验证成功时返回空字符串
} catch (err) {
return err.errors.join(',') // 验证失败时返回错误信息
}
},
})

export default () => (
<Form form={form} labelCol={6} wrapperCol={10}>
<Field
name="global_style_1"
title="email"
required
validator={{
yup: () => string().email(),
}}
component={[Input]}
decorator={[FormItem]}
/>
<Field
name="global_style_2"
title="最大值 30"
required
validator={{
yup: () => number().max(30),
}}
component={[NumberPicker]}
decorator={[FormItem]}
/>
<Field
name="global_style_3"
title="email"
required
validator={{
yup: () => string().email(),
}}
component={[Input]}
decorator={[FormItem]}
/>
</Form>
)
```

## 自定义格式校验

#### Markup Schema 案例
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@
"vue-eslint-parser": "^7.1.1",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1"
"webpack-dev-server": "^3.10.1",
"yup": "^1.4.0"
},
"repository": {
"type": "git",
Expand Down
25 changes: 25 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -16698,6 +16698,11 @@ property-expr@^1.5.0:
resolved "https://registry.yarnpkg.com/property-expr/-/property-expr-1.5.1.tgz#22e8706894a0c8e28d58735804f6ba3a3673314f"
integrity sha512-CGuc0VUTGthpJXL36ydB6jnbyOf/rAHFvmVrJlH+Rg0DqqLFQGAP6hIaxD/G0OAmBJPhXDHuEJigrp0e0wFV6g==

property-expr@^2.0.5:
version "2.0.6"
resolved "https://registry.npmmirror.com/property-expr/-/property-expr-2.0.6.tgz#f77bc00d5928a6c748414ad12882e83f24aec1e8"
integrity sha512-SVtmxhRE/CGkn3eZY1T6pC8Nln6Fr/lu1mKSgRud0eC73whjGfoAogbn78LkD8aFL0zz3bAFerKSnOl7NlErBA==

property-information@^5.0.0, property-information@^5.3.0, property-information@^5.5.0:
version "5.6.0"
resolved "https://registry.yarnpkg.com/property-information/-/property-information-5.6.0.tgz#61675545fb23002f245c6540ec46077d4da3ed69"
Expand Down Expand Up @@ -19967,6 +19972,11 @@ timsort@^0.3.0:
resolved "https://registry.yarnpkg.com/timsort/-/timsort-0.3.0.tgz#405411a8e7e6339fe64db9a234de11dc31e02bd4"
integrity sha1-QFQRqOfmM5/mTbmiNN4R3DHgK9Q=

tiny-case@^1.0.3:
version "1.0.3"
resolved "https://registry.npmmirror.com/tiny-case/-/tiny-case-1.0.3.tgz#d980d66bc72b5d5a9ca86fb7c9ffdb9c898ddd03"
integrity sha512-Eet/eeMhkO6TX8mnUteS9zgPbUMQa4I6Kkp5ORiBD5476/m+PIRiumP5tmh5ioJpH7k51Kehawy2UDfsnxxY8Q==

tiny-invariant@^1.0.2:
version "1.2.0"
resolved "https://registry.yarnpkg.com/tiny-invariant/-/tiny-invariant-1.2.0.tgz#a1141f86b672a9148c72e978a19a73b9b94a15a9"
Expand Down Expand Up @@ -20299,6 +20309,11 @@ type-fest@^0.8.1:
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d"
integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==

type-fest@^2.19.0:
version "2.19.0"
resolved "https://registry.npmmirror.com/type-fest/-/type-fest-2.19.0.tgz#88068015bb33036a598b952e55e9311a60fd3a9b"
integrity sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==

type-is@~1.6.18:
version "1.6.18"
resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131"
Expand Down Expand Up @@ -21633,6 +21648,16 @@ yup@^0.27.0:
synchronous-promise "^2.0.6"
toposort "^2.0.2"

yup@^1.4.0:
version "1.4.0"
resolved "https://registry.npmmirror.com/yup/-/yup-1.4.0.tgz#898dcd660f9fb97c41f181839d3d65c3ee15a43e"
integrity sha512-wPbgkJRCqIf+OHyiTBQoJiP5PFuAXaWiJK6AmYkzQAh5/c2K9hzSApBZG5wV9KoKSePF7sAxmNSvh/13YHkFDg==
dependencies:
property-expr "^2.0.5"
tiny-case "^1.0.3"
toposort "^2.0.2"
type-fest "^2.19.0"

zepto@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/zepto/-/zepto-1.2.0.tgz#e127bd9e66fd846be5eab48c1394882f7c0e4f98"
Expand Down

0 comments on commit 9001580

Please sign in to comment.