index.ts
961 Bytes
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
import type { Rule } from 'ant-design-vue/es/form'
export { default as JSONEditor } from './index.vue'
export const parseStringToJSON = <T = Recordable>(value: string) => {
let valid = false
try {
const json = JSON.parse(value) as T
typeof json === 'object' ? (valid = true) : (valid = false)
return { json, valid }
}
catch (error) {
return { json: null, valid }
}
}
export const JSONEditorValidator = (
message = 'JSON格式校验失败',
noEmpty = false,
emptyMessage = 'JSON不能为空对象',
): Rule[] => {
return [
{
validateTrigger: 'blur',
validator(_rule: Rule, value: any, _callback: Fn) {
const { valid, json } = parseStringToJSON(value)
if (valid) {
if (noEmpty && json && !Object.keys(json).length) return Promise.reject(emptyMessage)
return Promise.resolve()
}
else {
return Promise.reject(message)
}
},
},
]
}