forked from josdejong/jsoneditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
18_custom_validation.html
110 lines (97 loc) · 2.92 KB
/
18_custom_validation.html
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
<!DOCTYPE HTML>
<html>
<head>
<title>JSONEditor | Custom validation</title>
<link href="../dist/jsoneditor.css" rel="stylesheet" type="text/css">
<script src="../dist/jsoneditor.js"></script>
<style type="text/css">
body {
width: 600px;
font: 11pt sans-serif;
}
#jsoneditor {
width: 100%;
height: 500px;
}
</style>
</head>
<body>
<h1>Custom validation</h1>
<p>
This example demonstrates how to run custom validation on a JSON object.
The validation is available in all modes.
</p>
<div id="jsoneditor"></div>
<script>
var json = {
team: [
{
name: 'Joe',
age: 17
},
{
name: 'Sarah',
age: 13
},
{
name: 'Jack'
}
]
};
var options = {
mode: 'tree',
modes: ['code', 'text', 'tree'],
onValidate: function (json) {
// rules:
// - team, names, and ages must be filled in and be of correct type
// - a team must have 4 members
// - at lease one member of the team must be adult
var errors = [];
if (json && Array.isArray(json.team)) {
// check whether each team member has name and age filled in correctly
json.team.forEach(function (member, index) {
if (typeof member !== 'object') {
errors.push({ path: ['team', index], message: 'Member must be an object with properties "name" and "age"' })
}
if ('name' in member) {
if (typeof member.name !== 'string') {
errors.push({ path: ['team', index, 'name'], message: 'Name must be a string' })
}
}
else {
errors.push({ path: ['team', index], message: 'Required property "name"" missing' })
}
if ('age' in member) {
if (typeof member.age !== 'number') {
errors.push({ path: ['team', index, 'age'], message: 'Age must be a number' })
}
}
else {
errors.push({ path: ['team', index], message: 'Required property "age" missing' })
}
});
// check whether the team consists of exactly four members
if (json.team.length !== 4) {
errors.push({ path: ['team'], message: 'A team must have 4 members' })
}
// check whether there is at least one adult member in the team
var adults = json.team.filter(function (member) {
return member ? member.age >= 18 : false;
});
if (adults.length === 0) {
errors.push({ path: ['team'], message: 'A team must have at least one adult person (age >= 18)' })
}
}
else {
errors.push({ path: [], message: 'Required property "team" missing or not an Array' })
}
return errors;
}
};
// create the editor
var container = document.getElementById('jsoneditor');
var editor = new JSONEditor(container, options, json);
editor.expandAll();
</script>
</body>
</html>