-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
inputmask.js
432 lines (408 loc) · 13.3 KB
/
inputmask.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*
* Input Mask Core
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) Robin Herbots
* Licensed under the MIT license
*/
import defaults from "./defaults";
import definitions from "./definitions";
import $ from "./dependencyLibs/inputmask.dependencyLib";
import { EventRuler } from "./eventruler";
import window from "./global/window";
import { checkVal, unmaskedvalue } from "./inputHandling";
import { mask } from "./mask";
import { generateMaskSet, analyseMask } from "./mask-lexer";
import {
determineLastRequiredPosition,
getBuffer,
getBufferTemplate,
isMask
} from "./positioning";
import { isComplete } from "./validation";
import { getMaskTemplate } from "./validation-tests";
const document = window.document,
dataKey = "_inputmask_opts";
function Inputmask(alias, options, internal) {
// allow instanciating without new
if (!(this instanceof Inputmask)) {
return new Inputmask(alias, options, internal);
}
this.dependencyLib = $;
this.el = undefined;
this.events = {};
this.maskset = undefined;
if (internal !== true) {
// init options
if (Object.prototype.toString.call(alias) === "[object Object]") {
options = alias;
} else {
options = options || {};
if (alias) options.alias = alias;
}
this.opts = $.extend(true, {}, this.defaults, options);
this.noMasksCache = options && options.definitions !== undefined;
this.userOptions = options || {}; // user passed options
resolveAlias(this.opts.alias, options, this.opts);
}
// maskscope properties
this.refreshValue = false; // indicate a refresh from the inputvalue is needed (form.reset)
this.undoValue = undefined;
this.$el = undefined;
this.skipInputEvent = false; // skip when triggered from within inputmask
this.validationEvent = false;
this.ignorable = false;
// eslint-disable-next-line no-unused-expressions
this.maxLength;
this.mouseEnter = false;
this.clicked = 0;
this.originalPlaceholder = undefined; // needed for FF
this.isComposing = false; // keydowncode == 229 compositionevent fallback
this.hasAlternator = false;
}
Inputmask.prototype = {
dataAttribute: "data-inputmask", // data attribute prefix used for attribute binding
// options default
defaults,
definitions,
aliases: {}, // aliases definitions
masksCache: {},
i18n: {},
get isRTL() {
return this.opts.isRTL || this.opts.numericInput;
},
mask: function (elems) {
const that = this;
if (typeof elems === "string") {
elems =
document.getElementById(elems) || document.querySelectorAll(elems);
}
elems = elems.nodeName
? [elems]
: Array.isArray(elems)
? elems
: [].slice.call(elems); // [].slice as alternate for Array.from (Yandex browser)
elems.forEach(function (el, ndx) {
const scopedOpts = $.extend(true, {}, that.opts);
if (
importAttributeOptions(
el,
scopedOpts,
$.extend(true, {}, that.userOptions),
that.dataAttribute
)
) {
const maskset = generateMaskSet(scopedOpts, that.noMasksCache);
if (maskset !== undefined) {
if (el.inputmask !== undefined) {
el.inputmask.opts.autoUnmask = true; // force autounmasking when remasking
el.inputmask.remove();
}
// store inputmask instance on the input with element reference
el.inputmask = new Inputmask(undefined, undefined, true);
el.inputmask.opts = scopedOpts;
el.inputmask.noMasksCache = that.noMasksCache;
el.inputmask.userOptions = $.extend(true, {}, that.userOptions);
// el.inputmask.isRTL = scopedOpts.isRTL || scopedOpts.numericInput;
el.inputmask.el = el;
el.inputmask.$el = $(el);
el.inputmask.maskset = maskset;
$.data(el, dataKey, that.userOptions);
mask.call(el.inputmask);
}
}
});
return elems && elems[0] ? elems[0].inputmask || this : this;
},
option: function (options, noremask) {
// set extra options || retrieve value of a current option
if (typeof options === "string") {
return this.opts[options];
} else if (typeof options === "object") {
$.extend(this.userOptions, options); // user passed options
// remask
if (this.el && noremask !== true) {
this.mask(this.el);
}
return this;
}
},
unmaskedvalue: function (value) {
this.maskset =
this.maskset || generateMaskSet(this.opts, this.noMasksCache);
if (this.el === undefined || value !== undefined) {
const valueBuffer = (
typeof this.opts.onBeforeMask === "function"
? this.opts.onBeforeMask.call(this, value, this.opts) || value
: value
).split("");
checkVal.call(this, undefined, false, false, valueBuffer);
if (typeof this.opts.onBeforeWrite === "function")
this.opts.onBeforeWrite.call(
this,
undefined,
getBuffer.call(this),
0,
this.opts
);
}
return unmaskedvalue.call(this, this.el);
},
remove: function () {
if (this.el) {
$.data(this.el, dataKey, null); // invalidate
// writeout the value
const cv = this.opts.autoUnmask
? unmaskedvalue(this.el)
: this._valueGet(this.opts.autoUnmask);
if (cv !== getBufferTemplate.call(this).join(""))
this._valueSet(cv, this.opts.autoUnmask);
else this._valueSet("");
// unbind all events
EventRuler.off(this.el);
// restore the value property
let valueProperty;
if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
valueProperty = Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(this.el),
"value"
);
if (valueProperty) {
if (this.__valueGet) {
Object.defineProperty(this.el, "value", {
get: this.__valueGet,
set: this.__valueSet,
configurable: true
});
}
}
} else if (
document.__lookupGetter__ &&
this.el.__lookupGetter__("value")
) {
if (this.__valueGet) {
this.el.__defineGetter__("value", this.__valueGet);
this.el.__defineSetter__("value", this.__valueSet);
}
}
// clear data
this.el.inputmask = undefined;
}
return this.el;
},
getemptymask: function () {
// return the default (empty) mask value, usefull for setting the default value in validation
this.maskset =
this.maskset || generateMaskSet(this.opts, this.noMasksCache);
return (
this.isRTL
? getBufferTemplate.call(this).reverse()
: getBufferTemplate.call(this)
).join("");
},
hasMaskedValue: function () {
// check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
return !this.opts.autoUnmask;
},
isComplete: function () {
this.maskset =
this.maskset || generateMaskSet(this.opts, this.noMasksCache);
return isComplete.call(this, getBuffer.call(this));
},
getmetadata: function () {
// return mask metadata if exists
this.maskset =
this.maskset || generateMaskSet(this.opts, this.noMasksCache);
if (Array.isArray(this.maskset.metadata)) {
let maskTarget = getMaskTemplate.call(this, true, 0, false).join("");
this.maskset.metadata.forEach(function (mtdt) {
if (mtdt.mask === maskTarget) {
maskTarget = mtdt;
return false;
}
return true;
});
return maskTarget;
}
return this.maskset.metadata;
},
isValid: function (value) {
this.maskset =
this.maskset || generateMaskSet(this.opts, this.noMasksCache);
if (value) {
const valueBuffer = (
typeof this.opts.onBeforeMask === "function"
? this.opts.onBeforeMask.call(this, value, this.opts) || value
: value
).split("");
checkVal.call(this, undefined, true, false, valueBuffer);
} else {
value = this.isRTL
? getBuffer.call(this).slice().reverse().join("")
: getBuffer.call(this).join("");
}
let buffer = getBuffer.call(this),
rl = determineLastRequiredPosition.call(this),
lmib = buffer.length - 1;
for (; lmib > rl; lmib--) {
if (isMask.call(this, lmib)) break;
}
buffer.splice(rl, lmib + 1 - rl);
return (
isComplete.call(this, buffer) &&
value ===
(this.isRTL
? getBuffer.call(this).slice().reverse().join("")
: getBuffer.call(this).join(""))
);
},
format: function (value, metadata) {
this.maskset =
this.maskset || generateMaskSet(this.opts, this.noMasksCache);
const valueBuffer = (
typeof this.opts.onBeforeMask === "function"
? this.opts.onBeforeMask.call(this, value, this.opts) || value
: value
).split("");
checkVal.call(this, undefined, true, false, valueBuffer);
const formattedValue = this.isRTL
? getBuffer.call(this).slice().reverse().join("")
: getBuffer.call(this).join("");
return metadata
? {
value: formattedValue,
metadata: this.getmetadata()
}
: formattedValue;
},
setValue: function (value) {
if (this.el) {
$(this.el).trigger("setvalue", [value]);
}
},
analyseMask
};
function resolveAlias(aliasStr, options, opts) {
const aliasDefinition = Inputmask.prototype.aliases[aliasStr];
if (aliasDefinition) {
if (aliasDefinition.alias)
resolveAlias(aliasDefinition.alias, undefined, opts); // alias is another alias
$.extend(true, opts, aliasDefinition); // merge alias definition in the options
$.extend(true, opts, options); // reapply extra given options
return true;
} // alias not found - try as mask
else if (opts.mask === null) {
opts.mask = aliasStr;
}
return false;
}
function importAttributeOptions(npt, opts, userOptions, dataAttribute) {
function importOption(option, optionData) {
const attrOption =
dataAttribute === "" ? option : dataAttribute + "-" + option;
optionData =
optionData !== undefined ? optionData : npt.getAttribute(attrOption);
if (optionData !== null) {
if (typeof optionData === "string") {
if (option.indexOf("on") === 0) {
optionData = window[optionData];
} // get function definition
else if (optionData === "false") {
optionData = false;
} else if (optionData === "true") optionData = true;
}
userOptions[option] = optionData;
}
}
if (opts.importDataAttributes === true) {
let attrOptions = npt.getAttribute(dataAttribute),
option,
dataoptions,
optionData,
p;
if (attrOptions && attrOptions !== "") {
attrOptions = attrOptions.replace(/'/g, '"');
dataoptions = JSON.parse("{" + attrOptions + "}");
}
// resolve aliases
if (dataoptions) {
// pickup alias from dataAttribute
optionData = undefined;
for (p in dataoptions) {
if (p.toLowerCase() === "alias") {
optionData = dataoptions[p];
break;
}
}
}
importOption("alias", optionData); // pickup alias from dataAttribute-alias
if (userOptions.alias) {
resolveAlias(userOptions.alias, userOptions, opts);
}
for (option in opts) {
if (dataoptions) {
optionData = undefined;
for (p in dataoptions) {
if (p.toLowerCase() === option.toLowerCase()) {
optionData = dataoptions[p];
break;
}
}
}
importOption(option, optionData);
}
}
$.extend(true, opts, userOptions);
// handle dir=rtl
if (npt.dir === "rtl" || opts.rightAlign) {
npt.style.textAlign = "right";
}
if (npt.dir === "rtl" || opts.numericInput) {
npt.dir = "ltr";
npt.removeAttribute("dir");
opts.isRTL = true;
}
return Object.keys(userOptions).length;
}
// apply defaults, definitions, aliases
Inputmask.extendDefaults = function (options) {
$.extend(true, Inputmask.prototype.defaults, options);
};
Inputmask.extendDefinitions = function (definition) {
$.extend(true, Inputmask.prototype.definitions, definition);
};
Inputmask.extendAliases = function (alias) {
$.extend(true, Inputmask.prototype.aliases, alias);
};
// static fn on inputmask
Inputmask.format = function (value, options, metadata) {
return Inputmask(options).format(value, metadata);
};
Inputmask.unmask = function (value, options) {
return Inputmask(options).unmaskedvalue(value);
};
Inputmask.isValid = function (value, options) {
return Inputmask(options).isValid(value);
};
Inputmask.remove = function (elems) {
if (typeof elems === "string") {
elems = document.getElementById(elems) || document.querySelectorAll(elems);
}
elems = elems.nodeName ? [elems] : elems;
elems.forEach(function (el) {
if (el.inputmask) el.inputmask.remove();
});
};
Inputmask.setValue = function (elems, value) {
if (typeof elems === "string") {
elems = document.getElementById(elems) || document.querySelectorAll(elems);
}
elems = elems.nodeName ? [elems] : elems;
elems.forEach(function (el) {
if (el.inputmask) el.inputmask.setValue(value);
else $(el).trigger("setvalue", [value]);
});
};
Inputmask.dependencyLib = $;
// make inputmask available
window.Inputmask = Inputmask;
export default Inputmask;