Eagle

格式检验

2019-12-24

校验 xml 格式

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
validateContent = xmlContent => {
//errorCode 0是xml正确,1是xml错误,2是无法验证
var xmlDoc,
errorMessage,
errorCode = 0;
// code for IE
if (window.ActiveXObject) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlContent);

if (xmlDoc.parseError.errorCode != 0) {
errorMessage = "错误code: " + xmlDoc.parseError.errorCode + "\n";
errorMessage = errorMessage + "错误原因: " + xmlDoc.parseError.reason;
errorMessage = errorMessage + "错误位置: " + xmlDoc.parseError.line;
errorCode = 1;
} else {
errorMessage = "格式正确";
}
}
// code for Mozilla, Firefox, Opera, chrome, safari,etc.
else if (document.implementation.createDocument) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlContent, "text/xml");
var error = xmlDoc.getElementsByTagName("parsererror");
if (error.length > 0) {
if (xmlDoc.documentElement.nodeName == "parsererror") {
errorCode = 1;
errorMessage = xmlDoc.documentElement.childNodes[0].nodeValue;
} else {
errorCode = 1;
errorMessage = xmlDoc.getElementsByTagName("parsererror")[0].innerText;
}
} else {
errorMessage = "格式正确";
}
} else {
errorCode = 2;
errorMessage = "浏览器不支持验证,无法验证xml正确性";
}

return {
msg: errorMessage,
errorCode
};
};

json 格式校验

1
2
3
4
5
6
7
8
try {
const jsonFileContent = JSON.parse(fileContent);
if (typeof jsonFileContent == "object") {
formatValidate = true;
}
} catch (error) {
err("输入格式不正确,请输入正确JSON格式");
}
Tags: js