-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
server-validate.spec.ts
136 lines (127 loc) · 2.76 KB
/
server-validate.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import { createForm, Form } from '@formily/core'
import { ISchema, Schema, SchemaKey } from '../'
// 这是schema
const schemaJson = {
type: 'object',
title: 'xxx配置',
properties: {
string: {
type: 'string',
title: 'string',
maxLength: 5,
required: true,
},
number: {
type: 'number',
title: 'number',
required: true,
},
url: {
type: 'string',
title: 'url',
format: 'url',
},
arr: {
type: 'array',
title: 'array',
maxItems: 2,
required: true,
items: {
type: 'object',
properties: {
string: {
type: 'string',
title: 'string',
required: true,
},
},
},
},
},
}
// 这是需要校验的数据
const schemaData = {
string: '123456', // 超过5个字
// number 字段不存在
url: 'xxxxx', // 不合法的url
arr: [
{
string: '1',
},
{
string: '2',
},
{
// 数组超出2项
string: '', // 没有填
},
],
}
function recursiveField(
form: Form,
schema: ISchema,
basePath?: string,
name?: SchemaKey
) {
const fieldSchema = new Schema(schema)
const fieldProps = fieldSchema.toFieldProps()
function recursiveProperties(propBasePath?: string) {
fieldSchema.mapProperties((propSchema, propName) => {
recursiveField(form, propSchema, propBasePath, propName)
})
}
if (name === undefined || name === null) {
recursiveProperties(basePath)
return
}
if (schema.type === 'object') {
const field = form.createObjectField({
...fieldProps,
name,
basePath,
})
recursiveProperties(field.address.toString())
} else if (schema.type === 'array') {
const field = form.createArrayField({
...fieldProps,
name,
basePath,
})
const fieldAddress = field.address.toString()
const fieldValues = form.getValuesIn(fieldAddress)
fieldValues.forEach((value: any, index: number) => {
if (schema.items) {
const itemsSchema = Array.isArray(schema.items)
? schema.items[index] || schema.items[0]
: schema.items
recursiveField(form, itemsSchema as ISchema, fieldAddress, index)
}
})
} else if (schema.type === 'void') {
const field = form.createVoidField({
...fieldProps,
name,
basePath,
})
recursiveProperties(field.address.toString())
} else {
form.createField({
...fieldProps,
name,
basePath,
})
}
}
test('server validate', async () => {
const form = createForm({
values: schemaData,
})
recursiveField(form, schemaJson)
let errors: any[]
try {
await form.validate()
} catch (e) {
errors = e
}
expect(errors).not.toBeUndefined()
})