-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinput-filter.js
45 lines (43 loc) · 1.27 KB
/
input-filter.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
function setInputFilter(textbox, inputFilter, errMsg) {
[
"input",
"keydown",
"keyup",
"mousedown",
"mouseup",
"select",
"contextmenu",
"drop",
"focusout",
].forEach(function (event) {
textbox.addEventListener(event, function (e) {
if (inputFilter(this.value)) {
// Accepted value.
if (["keydown", "mousedown", "focusout"].indexOf(e.type) >= 0) {
this.classList.remove("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
// Rejected value: restore the previous one.
this.classList.add("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
// Rejected value: nothing to restore.
this.value = "";
}
});
});
}
setInputFilter(
document.getElementById("font-size"),
function (value) {
return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp.
},
"Only digits and '.' are allowed"
);