forked from episphere/quest
-
Notifications
You must be signed in to change notification settings - Fork 1
/
validate.js
288 lines (238 loc) · 10.5 KB
/
validate.js
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { callExchangeValues } from "./questionnaire.js";
import { translate } from "./common.js";
export function validateInput(inputElement) {
let handlers = {
number: validate_number,
email: validate_email,
tel: validate_telephone,
date: validate_date,
text: validate_text,
month: validate_month,
checkbox: validate_count
}
// can't use inputElement.type ==> firefox doesn't accept input.type='month'
let inputElementType = inputElement.getAttribute("type")
if (inputElementType in handlers) {
// clear any old validation error
clearValidationError(inputElement)
// if the value is blank, if required error, else it is valid.
if (inputElement.value.length == 0) {
if (inputElement.hasAttribute("data-required")) {
validationError(inputElement, translate("validationInputEmptyField"));
}
return
}
handlers[inputElementType](inputElement)
} else {
console.log(`no handle for type: ${inputElementType}`)
console.log(inputElement)
}
}
export function clearValidationError(inputElement) {
if (inputElement &&
inputElement.nextElementSibling?.classList.contains('validation-container')) {
let errDiv = inputElement.nextElementSibling;
errDiv.parentNode.removeChild(errDiv)
inputElement.classList.remove("invalid");
inputElement.closest("form").classList.remove("invalid");
}
}
export function validationError(inputElement, errorMsg) {
let errSpan = null
let errDiv = null;
// either use the current error div
// or create a new one...
if (inputElement && inputElement.nextElementSibling?.classList.contains('validation-container')) {
errDiv = inputElement.nextElementSibling;
errSpan = inputElement.nextElementSibling.firstChild;
} else {
errDiv = document.createElement("div")
errDiv.classList.add('validation-container');
errSpan = document.createElement("span")
// styling should be performed by CSS
errDiv.style.minHeight = "30px";
errSpan.style.height = "inherit";
errSpan.style.color = "red";
errDiv.appendChild(errSpan);
inputElement.insertAdjacentElement("afterend", errDiv);
}
errSpan.innerText = errorMsg
inputElement.classList.add("invalid");
inputElement.closest("form").classList.add("invalid");
}
function validate_number(inputElement) {
callExchangeValues(inputElement);
let belowMin =
inputElement.dataset.min &&
math.evaluate(`${inputElement.value} < ${inputElement.dataset.min}`);
let aboveMax =
inputElement.dataset.max &&
math.evaluate(`${inputElement.value} > ${inputElement.dataset.max}`);
if (belowMin) {
validationError(inputElement, translate("validationNumberGreaterThan", [inputElement.dataset.min]));
} else if (aboveMax) {
validationError(inputElement, translate("validationNumberLessThan", [inputElement.dataset.max]));
} else {
clearValidationError(inputElement);
}
}
function validate_month(inputElement) {
// because type="month" is not supported on firefox be careful with the input...
let value = inputElement.value.trim();
// if we have a value, and it does not match a date
if (value.length > 0 && !/^\d{4}-\d{1,2}$/.test(value)) {
// check for month-year...
if (/^(\d{1,2})-(\d{4})$/.test(value)) {
let found = value.match(/(\d{1,2})-(\d{4})/)
value = `${found[2]}-${found[1]}`;
inputElement.value = value;
} else {
validationError(inputElement, translate("validationMonthFormat"));
return;
}
}
// at this point, we should have a date in the form YYYY-MM...
let selectedDate = new Date(value);
if (isNaN(selectedDate.getTime())) {
validationError(inputElement, translate("validationMonthInvalid"));
return;
}
let minDate = (inputElement.dataset.minDate) ? new Date(decodeURIComponent(inputElement.dataset.minDate)) : undefined
let maxDate = (inputElement.dataset.maxDate) ? new Date(decodeURIComponent(inputElement.dataset.maxDate)) : undefined
let before_min_date = minDate && selectedDate < minDate
let after_max_date = maxDate && selectedDate > maxDate
// When input type='month' is supported, out of range values aren't selectable on the calendar.
// validationError shows when type="month" is not supported. Match expected text input format.
if (before_min_date) {
validationError(inputElement, translate("validationMonthAfter", [minDate.getUTCFullYear(), (minDate.getUTCMonth() + 1).toString().padStart(2, '0')]));
} else if (after_max_date) {
validationError(inputElement, translate("validationMonthBefore", [maxDate.getUTCFullYear(), (maxDate.getUTCMonth() + 1).toString().padStart(2, '0')]));
} else {
clearValidationError(inputElement)
}
}
function validate_date(inputElement) {
let minDate = (inputElement.dataset.minDate) ? new Date(inputElement.dataset.minDate + "GMT") : undefined
let maxDate = (inputElement.dataset.maxDate) ? new Date(inputElement.dataset.maxDate + "GMT") : undefined
let selectedDate = new Date(inputElement.value)
let before_min_date = minDate && selectedDate < minDate
let after_max_date = maxDate && selectedDate > maxDate
if (before_min_date) {
validationError(inputElement, translate("validationDateAfter", [minDate.getUTCMonth() + 1, minDate.getUTCDate(), minDate.getUTCFullYear()]));
} else if (after_max_date) {
validationError(inputElement, translate("validationDateBefore", [maxDate.getUTCMonth() + 1, maxDate.getUTCDate(), maxDate.getUTCFullYear()]));
} else {
clearValidationError(inputElement);
}
}
function validate_email(inputElement) {
console.log("in validate email", inputElement)
let emailRegEx = /\S+@\S+\.\S+/;
if (!emailRegEx.test(inputElement.value)) {
validationError(inputElement, translate("validationEmailAddress"));
} else {
clearValidationError(inputElement);
}
}
function validate_telephone(inputElement) {
console.log("in validate telephone", inputElement)
if (inputElement.value.length < 12) {
validationError(inputElement, translate("validationPhoneNumber"));
} else {
clearValidationError(inputElement);
}
}
function validate_text(inputElement) {
// validate a SSN...
if (inputElement.classList.contains("SSN")) {
if (!/^(?!9|000|666)(?!111-?11-?1111|333-?33-?3333|078-?05-?1120|219-?09-?9999)\d{3}-?(?!00)\d{2}-?(?!0000)\d{4}/gm.test(inputElement.value)) {
validationError(inputElement, translate("validationSocialFull"));
return;
} else {
clearValidationError(inputElement)
}
// if you are a SSN, you cannot be a 4-digit SSN and the length is set...
}
// validate a 4 digit SSN
if (inputElement.classList.contains("SSNsm")) {
if (!/^(?!0000)\d{4}/.test(inputElement.value)) {
validationError(inputElement, translate("validationSocialPartial"));
return;
} else {
clearValidationError(inputElement)
}
}
if (inputElement.classList.contains("zipcode")) {
let patternRegex = new RegExp(inputElement.getAttribute("pattern"));
console.log(inputElement.value, "===>", patternRegex.test(inputElement.value));
if (!patternRegex.test(inputElement.value)) {
validationError(inputElement, translate("validationZipCode"))
return;
}
clearValidationError(inputElement)
}
// check string length of text response
if ("minlen" in inputElement.dataset || "maxlen" in inputElement.dataset) {
let textLen = inputElement.value.length;
// the user has not entered anything. Dont bark yet...
if (textLen == 0) {
clearValidationError(inputElement);
return;
}
let hasMin = "minlen" in inputElement.dataset
let hasMax = "maxlen" in inputElement.dataset
let minLen = inputElement.dataset.minlen ?? -1
let maxLen = inputElement.dataset.maxlen ?? -2
let valueLen = inputElement.value.length
if (minLen == maxLen && valueLen != minLen) {
if (valueLen < minLen) {
validationError(inputElement, translate("validationTextShortExact", [minLen]));
}
else {
validationError(inputElement, translate("validationTextLongExact", [minLen]));
}
return;
}
if (hasMin && valueLen < minLen) {
validationError(inputElement, translate("validationTextShort", [minLen]));
return;
}
if (hasMax && valueLen > maxLen) {
validationError(inputElement, translate("validationTextLong", [maxLen]));
return
}
clearValidationError(inputElement)
}
let checkConfirmation = "confirm" in inputElement.dataset || "conformationFor" in inputElement.dataset;
if (checkConfirmation) {
let otherId = inputElement.dataset.confirm ?? inputElement.dataset.conformationFor
let otherElement = document.getElementById(otherId)
if (otherElement.value != inputElement.value) {
validationError(inputElement, translate("validationMismatch"));
validationError(otherElement, translate("validationMismatch"));
} else {
clearValidationError(inputElement)
clearValidationError(otherElement)
}
}
}
function validate_count(inputElement) {
let hasMin = 'minCount' in inputElement.form?.dataset;
let hasMax = 'maxCount' in inputElement.form?.dataset;
if (hasMin || hasMax) {
let minCount = inputElement.form.dataset.minCount;
let maxCount = inputElement.form.dataset.maxCount;
let selectedCount = inputElement.form.querySelectorAll(`[name=${inputElement.name}]:checked`).length;
let lastElement = inputElement.form.querySelectorAll(`[name=${inputElement.name}]`);
lastElement = lastElement.item(lastElement.length - 1).closest(".response");
if (hasMin && selectedCount < minCount) {
validationError(lastElement, translate("validationCountMore", [selectedCount, minCount]));
}
else if (hasMax && selectedCount > maxCount) {
validationError(lastElement, translate("validationCountLess", [selectedCount, maxCount]));
}
else {
clearValidationError(lastElement)
}
}
}