index.ts
955 Bytes
import { Rule } from '/@/components/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);
}
},
},
];
};