Socket
Socket
Sign inDemoInstall

inputmask

Package Overview
Dependencies
0
Maintainers
1
Versions
181
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 5.0.8-beta.17 to 5.0.8-beta.25

4

lib/eventhandlers.js

@@ -154,5 +154,3 @@ import {

keyupEvent: function (e) {
const inputmask = this.inputmask,
$ = inputmask.dependencyLib,
input = this;
const inputmask = this.inputmask;

@@ -159,0 +157,0 @@ if (inputmask.isComposing) {

@@ -16,328 +16,328 @@ /*

class DateObject {
constructor(mask, format, opts) {
this.mask = mask;
this.format = format;
this.opts = opts;
this._date = new Date(1, 0, 1);
this.initDateObject(mask, this.opts);
}
constructor(mask, format, opts) {
this.mask = mask;
this.format = format;
this.opts = opts;
this._date = new Date(1, 0, 1);
this.initDateObject(mask, this.opts);
}
get date() {
if (this._date === undefined) {
this._date = new Date(1, 0, 1);
this.initDateObject(undefined, this.opts);
}
return this._date;
}
get date() {
if (this._date === undefined) {
this._date = new Date(1, 0, 1);
this.initDateObject(undefined, this.opts);
}
return this._date;
}
initDateObject(mask, opts) {
let match;
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(this.format))) {
let dynMatches = new RegExp("\\d+$").exec(match[0]),
fcode = dynMatches ? (match[0][0] + "x") : match[0],
value;
if (mask !== undefined) {
if (dynMatches) {
let lastIndex = getTokenizer(opts).lastIndex,
tokanMatch = getTokenMatch(match.index, opts);
getTokenizer(opts).lastIndex = lastIndex;
value = mask.slice(0, mask.indexOf(tokanMatch.nextMatch[0]));
} else {
value = mask.slice(0, fcode.length);
}
mask = mask.slice(value.length);
}
initDateObject(mask, opts) {
let match;
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(this.format))) {
let dynMatches = new RegExp("\\d+$").exec(match[0]),
fcode = dynMatches ? (match[0][0] + "x") : match[0],
value;
if (mask !== undefined) {
if (dynMatches) {
let lastIndex = getTokenizer(opts).lastIndex,
tokenMatch = getTokenMatch(match.index, opts);
getTokenizer(opts).lastIndex = lastIndex;
value = mask.slice(0, mask.indexOf(tokenMatch.nextMatch[0]));
} else {
value = mask.slice(0, (formatCode[fcode] && formatCode[fcode][4]) || fcode.length);
}
mask = mask.slice(value.length);
}
if (Object.prototype.hasOwnProperty.call(formatCode, fcode)) {
this.setValue(this, value, fcode, formatCode[fcode][2], formatCode[fcode][1]);
}
}
}
if (Object.prototype.hasOwnProperty.call(formatCode, fcode)) {
this.setValue(this, value, fcode, formatCode[fcode][2], formatCode[fcode][1]);
}
}
}
setValue(dateObj, value, fcode, targetProp, dateOperation) {
if (value !== undefined) {
dateObj[targetProp] = targetProp === "ampm" ? value : value.replace(/[^0-9]/g, "0");
dateObj["raw" + targetProp] = value.replace(/\s/g, "_");
}
if (dateOperation !== undefined) {
let datavalue = dateObj[targetProp];
if ((targetProp === "day" && parseInt(datavalue) === 29) || (targetProp === "month" && parseInt(datavalue) === 2)) {
if (parseInt(dateObj.day) === 29 && parseInt(dateObj.month) === 2 && (dateObj.year === "" || dateObj.year === undefined)) {
//set temporary leap year in dateObj
dateObj._date.setFullYear(2012, 1, 29);
}
}
if (targetProp === "day") {
useDateObject = true;
if (parseInt(datavalue) === 0)
datavalue = 1;
}
if (targetProp === "month")
useDateObject = true;
if (targetProp === "year") {
useDateObject = true;
if (datavalue.length < 4)
datavalue = pad(datavalue, 4, true);
}
if (datavalue !== "" && !isNaN(datavalue)) dateOperation.call(dateObj._date, datavalue);
if (targetProp === "ampm")
dateOperation.call(dateObj._date, datavalue);
}
}
setValue(dateObj, value, fcode, targetProp, dateOperation) {
if (value !== undefined) {
dateObj[targetProp] = targetProp === "ampm" ? value : value.replace(/[^0-9]/g, "0");
dateObj["raw" + targetProp] = value.replace(/\s/g, "_");
}
if (dateOperation !== undefined) {
let datavalue = dateObj[targetProp];
if ((targetProp === "day" && parseInt(datavalue) === 29) || (targetProp === "month" && parseInt(datavalue) === 2)) {
if (parseInt(dateObj.day) === 29 && parseInt(dateObj.month) === 2 && (dateObj.year === "" || dateObj.year === undefined)) {
//set temporary leap year in dateObj
dateObj._date.setFullYear(2012, 1, 29);
}
}
if (targetProp === "day") {
useDateObject = true;
if (parseInt(datavalue) === 0)
datavalue = 1;
}
if (targetProp === "month")
useDateObject = true;
if (targetProp === "year") {
useDateObject = true;
if (datavalue.length < 4)
datavalue = pad(datavalue, 4, true);
}
if (datavalue !== "" && !isNaN(datavalue)) dateOperation.call(dateObj._date, datavalue);
if (targetProp === "ampm")
dateOperation.call(dateObj._date, datavalue);
}
}
reset() {
this._date = new Date(1, 0, 1);
}
reset() {
this._date = new Date(1, 0, 1);
}
reInit() {
this._date = undefined;
this.date;
}
reInit() {
this._date = undefined;
this.date;
}
}
let currentYear = new Date().getFullYear(),
useDateObject = false,
//supported codes for formatting
//http://blog.stevenlevithan.com/archives/date-time-format
//https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings?view=netframework-4.7
formatCode = { //regex, valueSetter, type, displayformatter
d: ["[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", Date.prototype.getDate], //Day of the month as digits; no leading zero for single-digit days.
dd: ["0[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", function () {
return pad(Date.prototype.getDate.call(this), 2);
}], //Day of the month as digits; leading zero for single-digit days.
ddd: [""], //Day of the week as a three-letter abbreviation.
dddd: [""], //Day of the week as its full name.
m: ["[1-9]|1[012]", function (val) {
let mval = val ? parseInt(val) : 0;
if (mval > 0) mval--;
return Date.prototype.setMonth.call(this, mval);
}, "month", function () {
return Date.prototype.getMonth.call(this) + 1;
}], //Month as digits; no leading zero for single-digit months.
mm: ["0[1-9]|1[012]", function (val) {
let mval = val ? parseInt(val) : 0;
if (mval > 0) mval--;
return Date.prototype.setMonth.call(this, mval);
}, "month", function () {
return pad(Date.prototype.getMonth.call(this) + 1, 2);
}], //Month as digits; leading zero for single-digit months.
mmm: [""], //Month as a three-letter abbreviation.
mmmm: [""], //Month as its full name.
yy: ["[0-9]{2}", Date.prototype.setFullYear, "year", function () {
return pad(Date.prototype.getFullYear.call(this), 2);
}], //Year as last two digits; leading zero for years less than 10.
yyyy: ["[0-9]{4}", Date.prototype.setFullYear, "year", function () {
return pad(Date.prototype.getFullYear.call(this), 4);
}],
h: ["[1-9]|1[0-2]", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no leading zero for single-digit hours (12-hour clock).
hh: ["0[1-9]|1[0-2]", Date.prototype.setHours, "hours", function () {
return pad(Date.prototype.getHours.call(this), 2);
}], //Hours; leading zero for single-digit hours (12-hour clock).
hx: [function (x) {
return `[0-9]{${x}}`;
}, Date.prototype.setHours, "hours", function (x) {
return Date.prototype.getHours;
}], //Hours; no limit; set maximum digits
H: ["1?[0-9]|2[0-3]", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no leading zero for single-digit hours (24-hour clock).
HH: ["0[0-9]|1[0-9]|2[0-3]", Date.prototype.setHours, "hours", function () {
return pad(Date.prototype.getHours.call(this), 2);
}], //Hours; leading zero for single-digit hours (24-hour clock).
Hx: [function (x) {
return `[0-9]{${x}}`;
}, Date.prototype.setHours, "hours", function (x) {
return function () {
return pad(Date.prototype.getHours.call(this), x);
};
}], //Hours; no limit; set maximum digits
M: ["[1-5]?[0-9]", Date.prototype.setMinutes, "minutes", Date.prototype.getMinutes], //Minutes; no leading zero for single-digit minutes. Uppercase M unlike CF timeFormat's m to avoid conflict with months.
MM: ["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setMinutes, "minutes", function () {
return pad(Date.prototype.getMinutes.call(this), 2);
}], //Minutes; leading zero for single-digit minutes. Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.
s: ["[1-5]?[0-9]", Date.prototype.setSeconds, "seconds", Date.prototype.getSeconds], //Seconds; no leading zero for single-digit seconds.
ss: ["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setSeconds, "seconds", function () {
return pad(Date.prototype.getSeconds.call(this), 2);
}], //Seconds; leading zero for single-digit seconds.
l: ["[0-9]{3}", Date.prototype.setMilliseconds, "milliseconds", function () {
return pad(Date.prototype.getMilliseconds.call(this), 3);
}], //Milliseconds. 3 digits.
L: ["[0-9]{2}", Date.prototype.setMilliseconds, "milliseconds", function () {
return pad(Date.prototype.getMilliseconds.call(this), 2);
}], //Milliseconds. 2 digits.
t: ["[ap]", setAMPM, "ampm", getAMPM, 1], //Lowercase, single-character time marker string: a or p.
tt: ["[ap]m", setAMPM, "ampm", getAMPM, 2], //two-character time marker string: am or pm.
T: ["[AP]", setAMPM, "ampm", getAMPM, 1], //single-character time marker string: A or P.
TT: ["[AP]M", setAMPM, "ampm", getAMPM, 2], //two-character time marker string: AM or PM.
Z: [".*", undefined, "Z", getTimeZoneAbbreviated], //US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500
o: [""], //GMT/UTC timezone offset, e.g. -0500 or +0230.
S: [""] //The date's ordinal suffix (st, nd, rd, or th).
},
formatAlias = {
isoDate: "yyyy-mm-dd", //2007-06-09
isoTime: "HH:MM:ss", //17:46:21
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", //2007-06-09T17:46:21
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" //2007-06-09T22:46:21Z
};
useDateObject = false,
//supported codes for formatting
//http://blog.stevenlevithan.com/archives/date-time-format
//https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings?view=netframework-4.7
formatCode = { //regex, valueSetter, type, displayformatter, #entries (optional)
d: ["[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", Date.prototype.getDate], //Day of the month as digits; no leading zero for single-digit days.
dd: ["0[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", function () {
return pad(Date.prototype.getDate.call(this), 2);
}], //Day of the month as digits; leading zero for single-digit days.
ddd: [""], //Day of the week as a three-letter abbreviation.
dddd: [""], //Day of the week as its full name.
m: ["[1-9]|1[012]", function (val) {
let mval = val ? parseInt(val) : 0;
if (mval > 0) mval--;
return Date.prototype.setMonth.call(this, mval);
}, "month", function () {
return Date.prototype.getMonth.call(this) + 1;
}], //Month as digits; no leading zero for single-digit months.
mm: ["0[1-9]|1[012]", function (val) {
let mval = val ? parseInt(val) : 0;
if (mval > 0) mval--;
return Date.prototype.setMonth.call(this, mval);
}, "month", function () {
return pad(Date.prototype.getMonth.call(this) + 1, 2);
}], //Month as digits; leading zero for single-digit months.
mmm: [""], //Month as a three-letter abbreviation.
mmmm: [""], //Month as its full name.
yy: ["[0-9]{2}", Date.prototype.setFullYear, "year", function () {
return pad(Date.prototype.getFullYear.call(this), 2);
}], //Year as last two digits; leading zero for years less than 10.
yyyy: ["[0-9]{4}", Date.prototype.setFullYear, "year", function () {
return pad(Date.prototype.getFullYear.call(this), 4);
}],
h: ["[1-9]|1[0-2]", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no leading zero for single-digit hours (12-hour clock).
hh: ["0[1-9]|1[0-2]", Date.prototype.setHours, "hours", function () {
return pad(Date.prototype.getHours.call(this), 2);
}], //Hours; leading zero for single-digit hours (12-hour clock).
hx: [function (x) {
return `[0-9]{${x}}`;
}, Date.prototype.setHours, "hours", function (x) {
return Date.prototype.getHours;
}], //Hours; no limit; set maximum digits
H: ["1?[0-9]|2[0-3]", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no leading zero for single-digit hours (24-hour clock).
HH: ["0[0-9]|1[0-9]|2[0-3]", Date.prototype.setHours, "hours", function () {
return pad(Date.prototype.getHours.call(this), 2);
}], //Hours; leading zero for single-digit hours (24-hour clock).
Hx: [function (x) {
return `[0-9]{${x}}`;
}, Date.prototype.setHours, "hours", function (x) {
return function () {
return pad(Date.prototype.getHours.call(this), x);
};
}], //Hours; no limit; set maximum digits
M: ["[1-5]?[0-9]", Date.prototype.setMinutes, "minutes", Date.prototype.getMinutes], //Minutes; no leading zero for single-digit minutes. Uppercase M unlike CF timeFormat's m to avoid conflict with months.
MM: ["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setMinutes, "minutes", function () {
return pad(Date.prototype.getMinutes.call(this), 2);
}], //Minutes; leading zero for single-digit minutes. Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.
s: ["[1-5]?[0-9]", Date.prototype.setSeconds, "seconds", Date.prototype.getSeconds], //Seconds; no leading zero for single-digit seconds.
ss: ["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setSeconds, "seconds", function () {
return pad(Date.prototype.getSeconds.call(this), 2);
}], //Seconds; leading zero for single-digit seconds.
l: ["[0-9]{3}", Date.prototype.setMilliseconds, "milliseconds", function () {
return pad(Date.prototype.getMilliseconds.call(this), 3);
}, 3], //Milliseconds. 3 digits.
L: ["[0-9]{2}", Date.prototype.setMilliseconds, "milliseconds", function () {
return pad(Date.prototype.getMilliseconds.call(this), 2);
}, 2], //Milliseconds. 2 digits.
t: ["[ap]", setAMPM, "ampm", getAMPM, 1], //Lowercase, single-character time marker string: a or p.
tt: ["[ap]m", setAMPM, "ampm", getAMPM, 2], //two-character time marker string: am or pm.
T: ["[AP]", setAMPM, "ampm", getAMPM, 1], //single-character time marker string: A or P.
TT: ["[AP]M", setAMPM, "ampm", getAMPM, 2], //two-character time marker string: AM or PM.
Z: [".*", undefined, "Z", getTimeZoneAbbreviated], //US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500
o: [""], //GMT/UTC timezone offset, e.g. -0500 or +0230.
S: [""] //The date's ordinal suffix (st, nd, rd, or th).
},
formatAlias = {
isoDate: "yyyy-mm-dd", //2007-06-09
isoTime: "HH:MM:ss", //17:46:21
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", //2007-06-09T17:46:21
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" //2007-06-09T22:46:21Z
};
function setAMPM(value) {
const hours = this.getHours();
if (value.toLowerCase().includes("p")) {
this.setHours(hours + 12);
// console.log("setAMPM + 12");
} else if (value.toLowerCase().includes("a") && hours >= 12) {
this.setHours(hours - 12);
}
const hours = this.getHours();
if (value.toLowerCase().includes("p")) {
this.setHours(hours + 12);
// console.log("setAMPM + 12");
} else if (value.toLowerCase().includes("a") && hours >= 12) {
this.setHours(hours - 12);
}
}
function getAMPM() {
let date = this,
hours = date.getHours();
hours = hours || 12;
return hours >= 12 ? "PM" : "AM";
let date = this,
hours = date.getHours();
hours = hours || 12;
return hours >= 12 ? "PM" : "AM";
}
function getTimeZoneAbbreviated() {
//not perfect, but ok for now
let date = this, {1: tz} = date.toString().match(/\((.+)\)/);
if (tz.includes(" ")) {
tz = tz.replace("-", " ").toUpperCase();
tz = tz.split(" ").map(([first]) => first).join("");
}
return tz;
//not perfect, but ok for now
let date = this, {1: tz} = date.toString().match(/\((.+)\)/);
if (tz.includes(" ")) {
tz = tz.replace("-", " ").toUpperCase();
tz = tz.split(" ").map(([first]) => first).join("");
}
return tz;
}
function formatcode(match) {
var dynMatches = new RegExp("\\d+$").exec(match[0]);
if (dynMatches && dynMatches[0] !== undefined) {
var fcode = formatCode[match[0][0] + "x"].slice("");
fcode[0] = fcode[0](dynMatches[0]);
fcode[3] = fcode[3](dynMatches[0]);
var dynMatches = new RegExp("\\d+$").exec(match[0]);
if (dynMatches && dynMatches[0] !== undefined) {
var fcode = formatCode[match[0][0] + "x"].slice("");
fcode[0] = fcode[0](dynMatches[0]);
fcode[3] = fcode[3](dynMatches[0]);
return fcode;
} else if (formatCode[match[0]]) {
return formatCode[match[0]];
}
return fcode;
} else if (formatCode[match[0]]) {
return formatCode[match[0]];
}
}
function getTokenizer(opts) {
if (!opts.tokenizer) {
var tokens = [], dyntokens = [];
for (var ndx in formatCode) {
if (/\.*x$/.test(ndx)) {
var dynToken = ndx[0] + "\\d+";
if (dyntokens.indexOf(dynToken) === -1) {
dyntokens.push(dynToken);
}
} else if (tokens.indexOf(ndx[0]) === -1) {
tokens.push(ndx[0]);
}
}
opts.tokenizer = "(" + (dyntokens.length > 0 ? dyntokens.join("|") + "|" : "") + tokens.join("+|") + ")+?|.";
opts.tokenizer = new RegExp(opts.tokenizer, "g");
}
if (!opts.tokenizer) {
var tokens = [], dyntokens = [];
for (var ndx in formatCode) {
if (/\.*x$/.test(ndx)) {
var dynToken = ndx[0] + "\\d+";
if (dyntokens.indexOf(dynToken) === -1) {
dyntokens.push(dynToken);
}
} else if (tokens.indexOf(ndx[0]) === -1) {
tokens.push(ndx[0]);
}
}
opts.tokenizer = "(" + (dyntokens.length > 0 ? dyntokens.join("|") + "|" : "") + tokens.join("+|") + ")+?|.";
opts.tokenizer = new RegExp(opts.tokenizer, "g");
}
return opts.tokenizer;
return opts.tokenizer;
}
function prefillYear(dateParts, currentResult, opts) {
if (dateParts.year !== dateParts.rawyear) {
var crrntyear = currentYear.toString(),
enteredPart = dateParts.rawyear.replace(/[^0-9]/g, ""),
currentYearPart = crrntyear.slice(0, enteredPart.length),
currentYearNextPart = crrntyear.slice(enteredPart.length);
if (enteredPart.length === 2 && enteredPart === currentYearPart) {
const entryCurrentYear = new Date(currentYear, dateParts.month - 1, dateParts.day);
if (dateParts.day == entryCurrentYear.getDate() && (!opts.max || opts.max.date.getTime() >= entryCurrentYear.getTime())) {
//update dateParts
dateParts.date.setFullYear(currentYear);
dateParts.year = crrntyear;
//update result
currentResult.insert = [{
pos: currentResult.pos + 1,
c: currentYearNextPart[0]
}, {
pos: currentResult.pos + 2,
c: currentYearNextPart[1]
}];
}
}
}
if (dateParts.year !== dateParts.rawyear) {
var crrntyear = currentYear.toString(),
enteredPart = dateParts.rawyear.replace(/[^0-9]/g, ""),
currentYearPart = crrntyear.slice(0, enteredPart.length),
currentYearNextPart = crrntyear.slice(enteredPart.length);
if (enteredPart.length === 2 && enteredPart === currentYearPart) {
const entryCurrentYear = new Date(currentYear, dateParts.month - 1, dateParts.day);
if (dateParts.day == entryCurrentYear.getDate() && (!opts.max || opts.max.date.getTime() >= entryCurrentYear.getTime())) {
//update dateParts
dateParts.date.setFullYear(currentYear);
dateParts.year = crrntyear;
//update result
currentResult.insert = [{
pos: currentResult.pos + 1,
c: currentYearNextPart[0]
}, {
pos: currentResult.pos + 2,
c: currentYearNextPart[1]
}];
}
}
}
return currentResult;
return currentResult;
}
function isValidDate(dateParts, currentResult, opts) {
if (!useDateObject) return true;
if (dateParts.rawday === undefined
|| (!isFinite(dateParts.rawday) && new Date(dateParts.date.getFullYear(), isFinite(dateParts.rawmonth) ? dateParts.month : dateParts.date.getMonth() + 1, 0).getDate() >= dateParts.day)
|| (dateParts.day == "29" && (!isFinite(dateParts.rawyear) || dateParts.rawyear === undefined || dateParts.rawyear === ""))
|| new Date(dateParts.date.getFullYear(), isFinite(dateParts.rawmonth) ? dateParts.month : dateParts.date.getMonth() + 1, 0).getDate() >= dateParts.day) {
return currentResult;
} else { //take corrective action if possible
if (dateParts.day == "29") {
var tokenMatch = getTokenMatch(currentResult.pos, opts);
if (tokenMatch.targetMatch[0] === "yyyy" && currentResult.pos - tokenMatch.targetMatchIndex === 2) {
currentResult.remove = currentResult.pos + 1;
return currentResult;
}
} else if (dateParts.month == "02" && dateParts.day == "30" && currentResult.c !== undefined) {
dateParts.day = "03";
dateParts.date.setDate(3);
dateParts.date.setMonth(1);
currentResult.insert = [{pos: currentResult.pos, c: "0"}, {pos: currentResult.pos + 1, c: currentResult.c}];
currentResult.caret = seekNext.call(this, currentResult.pos + 1);
return currentResult;
}
return false;
}
if (!useDateObject) return true;
if (dateParts.rawday === undefined
|| (!isFinite(dateParts.rawday) && new Date(dateParts.date.getFullYear(), isFinite(dateParts.rawmonth) ? dateParts.month : dateParts.date.getMonth() + 1, 0).getDate() >= dateParts.day)
|| (dateParts.day == "29" && (!isFinite(dateParts.rawyear) || dateParts.rawyear === undefined || dateParts.rawyear === ""))
|| new Date(dateParts.date.getFullYear(), isFinite(dateParts.rawmonth) ? dateParts.month : dateParts.date.getMonth() + 1, 0).getDate() >= dateParts.day) {
return currentResult;
} else { //take corrective action if possible
if (dateParts.day == "29") {
var tokenMatch = getTokenMatch(currentResult.pos, opts);
if (tokenMatch.targetMatch[0] === "yyyy" && currentResult.pos - tokenMatch.targetMatchIndex === 2) {
currentResult.remove = currentResult.pos + 1;
return currentResult;
}
} else if (dateParts.month == "02" && dateParts.day == "30" && currentResult.c !== undefined) {
dateParts.day = "03";
dateParts.date.setDate(3);
dateParts.date.setMonth(1);
currentResult.insert = [{pos: currentResult.pos, c: "0"}, {pos: currentResult.pos + 1, c: currentResult.c}];
currentResult.caret = seekNext.call(this, currentResult.pos + 1);
return currentResult;
}
return false;
}
}
function isDateInRange(dateParts, result, opts, maskset, fromCheckval) {
if (!result) return result;
if (result && opts.min) {
if (/*useDateObject && (dateParts["year"] === undefined || dateParts["yearSet"]) && */opts.min.date.getTime() === opts.min.date.getTime()) {
let match;
dateParts.reset();
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(opts.inputFormat))) {
var fcode;
if ((fcode = formatcode(match))) {
if (fcode[3]) {
var setFn = fcode[1];
var current = dateParts[fcode[2]],
minVal = opts.min[fcode[2]],
maxVal = opts.max ? opts.max[fcode[2]] : minVal,
curVal = [];
if (!result) return result;
if (result && opts.min) {
if (/*useDateObject && (dateParts["year"] === undefined || dateParts["yearSet"]) && */!isNaN(opts.min.date.getTime())) {
let match;
dateParts.reset();
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(opts.inputFormat))) {
var fcode;
if ((fcode = formatcode(match))) {
if (fcode[3]) {
var setFn = fcode[1];
var current = dateParts[fcode[2]],
minVal = opts.min[fcode[2]],
maxVal = opts.max ? opts.max[fcode[2]] : minVal,
curVal = [];
let forceCurrentValue = false;
for (let i = 0; i < minVal.length; i++) {
if (maskset.validPositions[i + match.index] === undefined && !forceCurrentValue) {
curVal[i] = minVal[i];
// ADD +1 to whoile
if (fcode[2] === "year" && current.length - 1 == i && minVal != maxVal)
curVal = (parseInt(curVal.join("")) + 1).toString().split("");
if (fcode[2] === "ampm" && minVal != maxVal && opts.min.date.getTime() > dateParts.date.getTime())
curVal[i] = maxVal[i];
} else {
curVal[i] = current[i];
forceCurrentValue = forceCurrentValue || current[i] > minVal[i];
}
}
let forceCurrentValue = false;
for (let i = 0; i < minVal.length; i++) {
if (maskset.validPositions[i + match.index] === undefined && !forceCurrentValue) {
curVal[i] = minVal[i];
// ADD +1 to whoile
if (fcode[2] === "year" && current.length - 1 == i && minVal != maxVal)
curVal = (parseInt(curVal.join("")) + 1).toString().split("");
if (fcode[2] === "ampm" && minVal != maxVal && opts.min.date.getTime() > dateParts.date.getTime())
curVal[i] = maxVal[i];
} else {
curVal[i] = current[i];
forceCurrentValue = forceCurrentValue || current[i] > minVal[i];
}
}
setFn.call(dateParts._date, curVal.join(""));
}
}
}
setFn.call(dateParts._date, curVal.join(""));
}
}
}
result = opts.min.date.getTime() <= dateParts.date.getTime();
dateParts.reInit();
}
}
result = opts.min.date.getTime() <= dateParts.date.getTime();
dateParts.reInit();
}
}
if (result && opts.max) {
if (opts.max.date.getTime() === opts.max.date.getTime()) {
result = opts.max.date.getTime() >= dateParts.date.getTime();
}
}
return result;
if (result && opts.max) {
if (!isNaN(opts.max.date.getTime())) {
result = opts.max.date.getTime() >= dateParts.date.getTime();
}
}
return result;
}

@@ -348,37 +348,37 @@

function parse(format, dateObjValue, opts, raw) {
//parse format to regex string
var mask = "", match, fcode;
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(format))) {
if (dateObjValue === undefined) {
if ((fcode = formatcode(match))) {
mask += "(" + fcode[0] + ")";
} else {
switch (match[0]) {
case "[":
mask += "(";
break;
case "]":
mask += ")?";
break;
default:
mask += escapeRegex(match[0]);
}
}
} else {
if ((fcode = formatcode(match))) {
if (raw !== true && fcode[3]) {
var getFn = fcode[3];
mask += getFn.call(dateObjValue.date);
} else if (fcode[2]) {
mask += dateObjValue["raw" + fcode[2]];
} else {
mask += match[0];
}
} else {
mask += match[0];
}
}
}
return mask;
//parse format to regex string
var mask = "", match, fcode;
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(format))) {
if (dateObjValue === undefined) {
if ((fcode = formatcode(match))) {
mask += "(" + fcode[0] + ")";
} else {
switch (match[0]) {
case "[":
mask += "(";
break;
case "]":
mask += ")?";
break;
default:
mask += escapeRegex(match[0]);
}
}
} else {
if ((fcode = formatcode(match))) {
if (raw !== true && fcode[3]) {
var getFn = fcode[3];
mask += getFn.call(dateObjValue.date);
} else if (fcode[2]) {
mask += dateObjValue["raw" + fcode[2]];
} else {
mask += match[0];
}
} else {
mask += match[0];
}
}
}
return mask;
}

@@ -388,39 +388,39 @@

function pad(val, len, right) {
val = String(val);
len = len || 2;
while (val.length < len) val = right ? val + "0" : "0" + val;
return val;
val = String(val);
len = len || 2;
while (val.length < len) val = right ? val + "0" : "0" + val;
return val;
}
function analyseMask(mask, format, opts) {
if (typeof mask === "string") {
return new DateObject(mask, format, opts);
} else if (mask && typeof mask === "object" && Object.prototype.hasOwnProperty.call(mask, "date")) {
return mask;
}
return undefined;
if (typeof mask === "string") {
return new DateObject(mask, format, opts);
} else if (mask && typeof mask === "object" && Object.prototype.hasOwnProperty.call(mask, "date")) {
return mask;
}
return undefined;
}
function importDate(dateObj, opts) {
return parse(opts.inputFormat, {date: dateObj}, opts);
return parse(opts.inputFormat, {date: dateObj}, opts);
}
function getTokenMatch(pos, opts) {
var calcPos = 0, targetMatch, match, matchLength = 0;
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(opts.inputFormat))) {
var dynMatches = new RegExp("\\d+$").exec(match[0]);
matchLength = dynMatches ? parseInt(dynMatches[0]) : match[0].length;
calcPos += matchLength;
if (calcPos >= pos + 1) {
targetMatch = match;
match = getTokenizer(opts).exec(opts.inputFormat);
break;
}
}
return {
targetMatchIndex: calcPos - matchLength,
nextMatch: match,
targetMatch: targetMatch
};
var calcPos = 0, targetMatch, match, matchLength = 0;
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(opts.inputFormat))) {
var dynMatches = new RegExp("\\d+$").exec(match[0]);
matchLength = dynMatches ? parseInt(dynMatches[0]) : match[0].length;
calcPos += matchLength;
if (calcPos >= pos + 1) {
targetMatch = match;
match = getTokenizer(opts).exec(opts.inputFormat);
break;
}
}
return {
targetMatchIndex: calcPos - matchLength,
nextMatch: match,
targetMatch: targetMatch
};
}

@@ -430,163 +430,163 @@

Inputmask.extendAliases({
"datetime": {
mask: function (opts) {
//do not allow numeric input in datetime alias
opts.numericInput = false;
"datetime": {
mask: function (opts) {
//do not allow numeric input in datetime alias
opts.numericInput = false;
//localize
formatCode.S = opts.i18n.ordinalSuffix.join("|");
//localize
formatCode.S = opts.i18n.ordinalSuffix.join("|");
opts.inputFormat = formatAlias[opts.inputFormat] || opts.inputFormat; //resolve possible formatAlias
opts.displayFormat = formatAlias[opts.displayFormat] || opts.displayFormat || opts.inputFormat; //resolve possible formatAlias
opts.outputFormat = formatAlias[opts.outputFormat] || opts.outputFormat || opts.inputFormat; //resolve possible formatAlias
opts.placeholder = opts.placeholder !== "" ? opts.placeholder : opts.inputFormat.replace(/[[\]]/, "");
opts.regex = parse(opts.inputFormat, undefined, opts);
opts.min = analyseMask(opts.min, opts.inputFormat, opts);
opts.max = analyseMask(opts.max, opts.inputFormat, opts);
return null; //migrate to regex mask
},
placeholder: "", //set default as none (~ auto); when a custom placeholder is passed it will be used
inputFormat: "isoDateTime", //format used to input the date
displayFormat: null, //visual format when the input looses focus
outputFormat: null, //unmasking format
min: null, //needs to be in the same format as the inputfornat
max: null, //needs to be in the same format as the inputfornat,
skipOptionalPartCharacter: "",
// Internationalization strings
i18n: {
dayNames: [
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
],
ordinalSuffix: ["st", "nd", "rd", "th"]
},
preValidation: function (buffer, pos, c, isSelection, opts, maskset, caretPos, strict) {
if (strict) return true;
if (isNaN(c) && buffer[pos] !== c) {
var tokenMatch = getTokenMatch(pos, opts);
if (tokenMatch.nextMatch && tokenMatch.nextMatch[0] === c && tokenMatch.targetMatch[0].length > 1) {
var validator = formatCode[tokenMatch.targetMatch[0]][0];
if (new RegExp(validator).test("0" + buffer[pos - 1])) {
buffer[pos] = buffer[pos - 1];
buffer[pos - 1] = "0";
return {
fuzzy: true,
buffer: buffer,
refreshFromBuffer: {start: pos - 1, end: pos + 1},
pos: pos + 1
};
}
}
}
return true;
},
postValidation: function (buffer, pos, c, currentResult, opts, maskset, strict, fromCheckval) {
const inputmask = this;
opts.inputFormat = formatAlias[opts.inputFormat] || opts.inputFormat; //resolve possible formatAlias
opts.displayFormat = formatAlias[opts.displayFormat] || opts.displayFormat || opts.inputFormat; //resolve possible formatAlias
opts.outputFormat = formatAlias[opts.outputFormat] || opts.outputFormat || opts.inputFormat; //resolve possible formatAlias
opts.placeholder = opts.placeholder !== "" ? opts.placeholder : opts.inputFormat.replace(/[[\]]/, "");
opts.regex = parse(opts.inputFormat, undefined, opts);
opts.min = analyseMask(opts.min, opts.inputFormat, opts);
opts.max = analyseMask(opts.max, opts.inputFormat, opts);
return null; //migrate to regex mask
},
placeholder: "", //set default as none (~ auto); when a custom placeholder is passed it will be used
inputFormat: "isoDateTime", //format used to input the date
displayFormat: null, //visual format when the input looses focus
outputFormat: null, //unmasking format
min: null, //needs to be in the same format as the inputfornat
max: null, //needs to be in the same format as the inputfornat,
skipOptionalPartCharacter: "",
// Internationalization strings
i18n: {
dayNames: [
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
],
ordinalSuffix: ["st", "nd", "rd", "th"]
},
preValidation: function (buffer, pos, c, isSelection, opts, maskset, caretPos, strict) {
if (strict) return true;
if (isNaN(c) && buffer[pos] !== c) {
var tokenMatch = getTokenMatch(pos, opts);
if (tokenMatch.nextMatch && tokenMatch.nextMatch[0] === c && tokenMatch.targetMatch[0].length > 1) {
var validator = formatCode[tokenMatch.targetMatch[0]][0];
if (new RegExp(validator).test("0" + buffer[pos - 1])) {
buffer[pos] = buffer[pos - 1];
buffer[pos - 1] = "0";
return {
fuzzy: true,
buffer: buffer,
refreshFromBuffer: {start: pos - 1, end: pos + 1},
pos: pos + 1
};
}
}
}
return true;
},
postValidation: function (buffer, pos, c, currentResult, opts, maskset, strict, fromCheckval) {
const inputmask = this;
if (strict) return true;
var tokenMatch, validator;
if (currentResult === false) { //try some shifting
tokenMatch = getTokenMatch(pos + 1, opts);
if (tokenMatch.targetMatch && tokenMatch.targetMatchIndex === pos && tokenMatch.targetMatch[0].length > 1 && formatCode[tokenMatch.targetMatch[0]] !== undefined) {
validator = formatCode[tokenMatch.targetMatch[0]][0];
} else {
tokenMatch = getTokenMatch(pos + 2, opts);
if (tokenMatch.targetMatch && tokenMatch.targetMatchIndex === pos + 1 && tokenMatch.targetMatch[0].length > 1 && formatCode[tokenMatch.targetMatch[0]] !== undefined) {
validator = formatCode[tokenMatch.targetMatch[0]][0];
}
}
if (validator !== undefined) {
if (maskset.validPositions[pos + 1] !== undefined && new RegExp(validator).test(c + "0")) {
buffer[pos] = c;
buffer[pos + 1] = "0";
currentResult = {
//insert: [{pos: pos, c: "0"}, {pos: pos + 1, c: c}],
pos: pos + 2, //this will triggeer a refreshfrombuffer
caret: pos
};
} else if (new RegExp(validator).test("0" + c)) {
buffer[pos] = "0";
buffer[pos + 1] = c;
currentResult = {
//insert: [{pos: pos, c: "0"}, {pos: pos + 1, c: c}],
pos: pos + 2 //this will triggeer a refreshfrombuffer
};
}
}
if (strict) return true;
var tokenMatch, validator;
if (currentResult === false) { //try some shifting
tokenMatch = getTokenMatch(pos + 1, opts);
if (tokenMatch.targetMatch && tokenMatch.targetMatchIndex === pos && tokenMatch.targetMatch[0].length > 1 && formatCode[tokenMatch.targetMatch[0]] !== undefined) {
validator = formatCode[tokenMatch.targetMatch[0]][0];
} else {
tokenMatch = getTokenMatch(pos + 2, opts);
if (tokenMatch.targetMatch && tokenMatch.targetMatchIndex === pos + 1 && tokenMatch.targetMatch[0].length > 1 && formatCode[tokenMatch.targetMatch[0]] !== undefined) {
validator = formatCode[tokenMatch.targetMatch[0]][0];
}
}
if (validator !== undefined) {
if (maskset.validPositions[pos + 1] !== undefined && new RegExp(validator).test(c + "0")) {
buffer[pos] = c;
buffer[pos + 1] = "0";
currentResult = {
//insert: [{pos: pos, c: "0"}, {pos: pos + 1, c: c}],
pos: pos + 2, //this will triggeer a refreshfrombuffer
caret: pos
};
} else if (new RegExp(validator).test("0" + c)) {
buffer[pos] = "0";
buffer[pos + 1] = c;
currentResult = {
//insert: [{pos: pos, c: "0"}, {pos: pos + 1, c: c}],
pos: pos + 2 //this will triggeer a refreshfrombuffer
};
}
}
if (currentResult === false) return currentResult;
}
if (currentResult === false) return currentResult;
}
if (currentResult.fuzzy) {
buffer = currentResult.buffer;
pos = currentResult.pos;
}
if (currentResult.fuzzy) {
buffer = currentResult.buffer;
pos = currentResult.pos;
}
//full validate target
tokenMatch = getTokenMatch(pos, opts);
if (tokenMatch.targetMatch && tokenMatch.targetMatch[0] && formatCode[tokenMatch.targetMatch[0]] !== undefined) {
let fcode = formatCode[tokenMatch.targetMatch[0]];
validator = fcode[0];
var part = buffer.slice(tokenMatch.targetMatchIndex, tokenMatch.targetMatchIndex + tokenMatch.targetMatch[0].length);
if (new RegExp(validator).test(part.join("")) === false && tokenMatch.targetMatch[0].length === 2 && maskset.validPositions[tokenMatch.targetMatchIndex] && maskset.validPositions[tokenMatch.targetMatchIndex + 1]) {
maskset.validPositions[tokenMatch.targetMatchIndex + 1].input = "0";
}
if (fcode[2] == "year") {
var _buffer = getMaskTemplate.call(inputmask, false, 1, undefined, true);
for (let i = pos + 1; i < buffer.length; i++) {
buffer[i] = _buffer[i];
delete maskset.validPositions[i];
}
}
}
//full validate target
tokenMatch = getTokenMatch(pos, opts);
if (tokenMatch.targetMatch && tokenMatch.targetMatch[0] && formatCode[tokenMatch.targetMatch[0]] !== undefined) {
let fcode = formatCode[tokenMatch.targetMatch[0]];
validator = fcode[0];
var part = buffer.slice(tokenMatch.targetMatchIndex, tokenMatch.targetMatchIndex + tokenMatch.targetMatch[0].length);
if (new RegExp(validator).test(part.join("")) === false && tokenMatch.targetMatch[0].length === 2 && maskset.validPositions[tokenMatch.targetMatchIndex] && maskset.validPositions[tokenMatch.targetMatchIndex + 1]) {
maskset.validPositions[tokenMatch.targetMatchIndex + 1].input = "0";
}
if (fcode[2] == "year") {
var _buffer = getMaskTemplate.call(inputmask, false, 1, undefined, true);
for (let i = pos + 1; i < buffer.length; i++) {
buffer[i] = _buffer[i];
delete maskset.validPositions[i];
}
}
}
var result = currentResult, dateParts = analyseMask(buffer.join(""), opts.inputFormat, opts);
if (result && dateParts.date.getTime() === dateParts.date.getTime()) { //check for a valid date ~ an invalid date returns NaN which isn't equal
if (opts.prefillYear) result = prefillYear(dateParts, result, opts);
result = isValidDate.call(inputmask, dateParts, result, opts);
result = isDateInRange(dateParts, result, opts, maskset, fromCheckval);
}
var result = currentResult, dateParts = analyseMask(buffer.join(""), opts.inputFormat, opts);
if (result && !isNaN(dateParts.date.getTime())) { //check for a valid date ~ an invalid date returns NaN which isn't equal
if (opts.prefillYear) result = prefillYear(dateParts, result, opts);
result = isValidDate.call(inputmask, dateParts, result, opts);
result = isDateInRange(dateParts, result, opts, maskset, fromCheckval);
}
if (pos !== undefined && result && currentResult.pos !== pos) {
return {
buffer: parse(opts.inputFormat, dateParts, opts).split(""),
refreshFromBuffer: {start: pos, end: currentResult.pos},
pos: currentResult.caret || currentResult.pos //correct caret position
};
}
if (pos !== undefined && result && currentResult.pos !== pos) {
return {
buffer: parse(opts.inputFormat, dateParts, opts).split(""),
refreshFromBuffer: {start: pos, end: currentResult.pos},
pos: currentResult.caret || currentResult.pos //correct caret position
};
}
return result;
},
onKeyDown: function (e, buffer, caretPos, opts) {
var input = this;
if (e.ctrlKey && e.keyCode === keyCode.RIGHT) {
input.inputmask._valueSet(importDate(new Date(), opts));
$(input).trigger("setvalue");
}
},
onUnMask: function (maskedValue, unmaskedValue, opts) {
return unmaskedValue ? parse(opts.outputFormat, analyseMask(maskedValue, opts.inputFormat, opts), opts, true) : unmaskedValue;
},
casing: function (elem, test, pos, validPositions) {
if (test.nativeDef.indexOf("[ap]") == 0) return elem.toLowerCase();
if (test.nativeDef.indexOf("[AP]") == 0) return elem.toUpperCase();
return elem;
},
onBeforeMask: function (initialValue, opts) {
if (Object.prototype.toString.call(initialValue) === "[object Date]") {
initialValue = importDate(initialValue, opts);
}
return result;
},
onKeyDown: function (e, buffer, caretPos, opts) {
var input = this;
if (e.ctrlKey && e.keyCode === keyCode.RIGHT) {
input.inputmask._valueSet(importDate(new Date(), opts));
$(input).trigger("setvalue");
}
},
onUnMask: function (maskedValue, unmaskedValue, opts) {
return unmaskedValue ? parse(opts.outputFormat, analyseMask(maskedValue, opts.inputFormat, opts), opts, true) : unmaskedValue;
},
casing: function (elem, test, pos, validPositions) {
if (test.nativeDef.indexOf("[ap]") == 0) return elem.toLowerCase();
if (test.nativeDef.indexOf("[AP]") == 0) return elem.toUpperCase();
return elem;
},
onBeforeMask: function (initialValue, opts) {
if (Object.prototype.toString.call(initialValue) === "[object Date]") {
initialValue = importDate(initialValue, opts);
}
return initialValue;
},
insertMode: false,
shiftPositions: false,
keepStatic: false,
inputmode: "numeric",
prefillYear: true //Allows to disable prefill for datetime year.
}
return initialValue;
},
insertMode: false,
shiftPositions: false,
keepStatic: false,
inputmode: "numeric",
prefillYear: true //Allows to disable prefill for datetime year.
}
});

@@ -15,224 +15,223 @@ /*

function autoEscape(txt, opts) {
var escapedTxt = "";
for (var i = 0; i < txt.length; i++) {
if (Inputmask.prototype.definitions[txt.charAt(i)] ||
opts.definitions[txt.charAt(i)] ||
opts.optionalmarker[0] === txt.charAt(i) ||
opts.optionalmarker[1] === txt.charAt(i) ||
opts.quantifiermarker[0] === txt.charAt(i) ||
opts.quantifiermarker[1] === txt.charAt(i) ||
opts.groupmarker[0] === txt.charAt(i) ||
opts.groupmarker[1] === txt.charAt(i) ||
opts.alternatormarker === txt.charAt(i)) {
escapedTxt += "\\" + txt.charAt(i);
} else {
escapedTxt += txt.charAt(i);
}
}
return escapedTxt;
var escapedTxt = "";
for (var i = 0; i < txt.length; i++) {
if (Inputmask.prototype.definitions[txt.charAt(i)] ||
opts.definitions[txt.charAt(i)] ||
opts.optionalmarker[0] === txt.charAt(i) ||
opts.optionalmarker[1] === txt.charAt(i) ||
opts.quantifiermarker[0] === txt.charAt(i) ||
opts.quantifiermarker[1] === txt.charAt(i) ||
opts.groupmarker[0] === txt.charAt(i) ||
opts.groupmarker[1] === txt.charAt(i) ||
opts.alternatormarker === txt.charAt(i)) {
escapedTxt += "\\" + txt.charAt(i);
} else {
escapedTxt += txt.charAt(i);
}
}
return escapedTxt;
}
function alignDigits(buffer, digits, opts, force) {
if (buffer.length > 0 && digits > 0 && (!opts.digitsOptional || force)) {
var radixPosition = buffer.indexOf(opts.radixPoint), negationBack = false;
if (opts.negationSymbol.back === buffer[buffer.length - 1]) {
negationBack = true;
buffer.length--;
}
if (buffer.length > 0 && digits > 0 && (!opts.digitsOptional || force)) {
var radixPosition = buffer.indexOf(opts.radixPoint), negationBack = false;
if (opts.negationSymbol.back === buffer[buffer.length - 1]) {
negationBack = true;
buffer.length--;
}
if (radixPosition === -1) {
buffer.push(opts.radixPoint);
radixPosition = buffer.length - 1;
}
for (var i = 1; i <= digits; i++) {
if (!isFinite(buffer[radixPosition + i])) {
buffer[radixPosition + i] = "0";
}
}
}
if (radixPosition === -1) {
buffer.push(opts.radixPoint);
radixPosition = buffer.length - 1;
}
for (var i = 1; i <= digits; i++) {
if (!isFinite(buffer[radixPosition + i])) {
buffer[radixPosition + i] = "0";
}
}
}
if (negationBack)
buffer.push(opts.negationSymbol.back);
return buffer;
if (negationBack)
buffer.push(opts.negationSymbol.back);
return buffer;
}
function findValidator(symbol, maskset) {
var posNdx = 0;
if (symbol === "+") {
for (posNdx in maskset.validPositions) ;
posNdx = seekNext.call(this, parseInt(posNdx));
}
for (var tstNdx in maskset.tests) {
tstNdx = parseInt(tstNdx);
if (tstNdx >= posNdx) {
for (var ndx = 0, ndxl = maskset.tests[tstNdx].length; ndx < ndxl; ndx++) {
if ((maskset.validPositions[tstNdx] === undefined || symbol === "-") && maskset.tests[tstNdx][ndx].match.def === symbol) {
return tstNdx + ((maskset.validPositions[tstNdx] !== undefined && symbol !== "-") ? 1 : 0);
}
}
}
}
return posNdx;
var posNdx = 0;
if (symbol === "+") {
posNdx = seekNext.call(this, maskset.validPositions.length - 1);
}
for (var tstNdx in maskset.tests) {
tstNdx = parseInt(tstNdx);
if (tstNdx >= posNdx) {
for (var ndx = 0, ndxl = maskset.tests[tstNdx].length; ndx < ndxl; ndx++) {
if ((maskset.validPositions[tstNdx] === undefined || symbol === "-") && maskset.tests[tstNdx][ndx].match.def === symbol) {
return tstNdx + ((maskset.validPositions[tstNdx] !== undefined && symbol !== "-") ? 1 : 0);
}
}
}
}
return posNdx;
}
function findValid(symbol, maskset) {
var ret = -1;
for (let ndx in maskset.validPositions) {
let tst = maskset.validPositions[ndx];
if (tst && tst.match.def === symbol) {
ret = parseInt(ndx);
break;
}
}
return ret;
var ret = -1;
for (let ndx = 0, vpl = maskset.validPositions.length; ndx < vpl; ndx++) {
let tst = maskset.validPositions[ndx];
if (tst && tst.match.def === symbol) {
ret = ndx;
break;
}
}
return ret;
}
function parseMinMaxOptions(opts) {
if (opts.parseMinMaxOptions === undefined) {
// convert min and max options
if (opts.min !== null) {
opts.min = opts.min.toString().replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
if (opts.radixPoint === ",") opts.min = opts.min.replace(opts.radixPoint, ".");
opts.min = isFinite(opts.min) ? parseFloat(opts.min) : NaN;
if (isNaN(opts.min)) opts.min = Number.MIN_VALUE;
}
if (opts.max !== null) {
opts.max = opts.max.toString().replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
if (opts.radixPoint === ",") opts.max = opts.max.replace(opts.radixPoint, ".");
opts.max = isFinite(opts.max) ? parseFloat(opts.max) : NaN;
if (isNaN(opts.max)) opts.max = Number.MAX_VALUE;
}
opts.parseMinMaxOptions = "done";
}
if (opts.parseMinMaxOptions === undefined) {
// convert min and max options
if (opts.min !== null) {
opts.min = opts.min.toString().replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
if (opts.radixPoint === ",") opts.min = opts.min.replace(opts.radixPoint, ".");
opts.min = isFinite(opts.min) ? parseFloat(opts.min) : NaN;
if (isNaN(opts.min)) opts.min = Number.MIN_VALUE;
}
if (opts.max !== null) {
opts.max = opts.max.toString().replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
if (opts.radixPoint === ",") opts.max = opts.max.replace(opts.radixPoint, ".");
opts.max = isFinite(opts.max) ? parseFloat(opts.max) : NaN;
if (isNaN(opts.max)) opts.max = Number.MAX_VALUE;
}
opts.parseMinMaxOptions = "done";
}
}
function genMask(opts) {
opts.repeat = 0;
//treat equal separator and radixpoint
if (opts.groupSeparator === opts.radixPoint && opts.digits && opts.digits !== "0") {
if (opts.radixPoint === ".") {
opts.groupSeparator = ",";
} else if (opts.radixPoint === ",") {
opts.groupSeparator = ".";
} else {
opts.groupSeparator = "";
}
}
//prevent conflict with default skipOptionalPartCharacter
if (opts.groupSeparator === " ") {
opts.skipOptionalPartCharacter = undefined;
}
opts.repeat = 0;
//treat equal separator and radixpoint
if (opts.groupSeparator === opts.radixPoint && opts.digits && opts.digits !== "0") {
if (opts.radixPoint === ".") {
opts.groupSeparator = ",";
} else if (opts.radixPoint === ",") {
opts.groupSeparator = ".";
} else {
opts.groupSeparator = "";
}
}
//prevent conflict with default skipOptionalPartCharacter
if (opts.groupSeparator === " ") {
opts.skipOptionalPartCharacter = undefined;
}
//enforce placeholder to single
if (opts.placeholder.length > 1) {
opts.placeholder = opts.placeholder.charAt(0);
}
//only allow radixfocus when placeholder = 0
if (opts.positionCaretOnClick === "radixFocus" && opts.placeholder === "") {
opts.positionCaretOnClick = "lvp";
}
//enforce placeholder to single
if (opts.placeholder.length > 1) {
opts.placeholder = opts.placeholder.charAt(0);
}
//only allow radixfocus when placeholder = 0
if (opts.positionCaretOnClick === "radixFocus" && opts.placeholder === "") {
opts.positionCaretOnClick = "lvp";
}
var decimalDef = "0", radixPointDef = opts.radixPoint;
if (opts.numericInput === true && opts.__financeInput === undefined) { //finance people input style
decimalDef = "1";
opts.positionCaretOnClick = opts.positionCaretOnClick === "radixFocus" ? "lvp" : opts.positionCaretOnClick;
opts.digitsOptional = false;
if (isNaN(opts.digits)) opts.digits = 2;
opts._radixDance = false;
radixPointDef = (opts.radixPoint === "," ? "?" : "!");
if (opts.radixPoint !== "" && opts.definitions[radixPointDef] === undefined) {
//update separator definition
opts.definitions[radixPointDef] = {};
opts.definitions[radixPointDef].validator = "[" + opts.radixPoint + "]";
opts.definitions[radixPointDef].placeholder = opts.radixPoint;
opts.definitions[radixPointDef].static = true;
opts.definitions[radixPointDef].generated = true; //forced marker as generated input
}
} else {
opts.__financeInput = false; //needed to keep original selection when remasking
opts.numericInput = true;
}
var decimalDef = "0", radixPointDef = opts.radixPoint;
if (opts.numericInput === true && opts.__financeInput === undefined) { //finance people input style
decimalDef = "1";
opts.positionCaretOnClick = opts.positionCaretOnClick === "radixFocus" ? "lvp" : opts.positionCaretOnClick;
opts.digitsOptional = false;
if (isNaN(opts.digits)) opts.digits = 2;
opts._radixDance = false;
radixPointDef = (opts.radixPoint === "," ? "?" : "!");
if (opts.radixPoint !== "" && opts.definitions[radixPointDef] === undefined) {
//update separator definition
opts.definitions[radixPointDef] = {};
opts.definitions[radixPointDef].validator = "[" + opts.radixPoint + "]";
opts.definitions[radixPointDef].placeholder = opts.radixPoint;
opts.definitions[radixPointDef].static = true;
opts.definitions[radixPointDef].generated = true; //forced marker as generated input
}
} else {
opts.__financeInput = false; //needed to keep original selection when remasking
opts.numericInput = true;
}
var mask = "[+]", altMask;
mask += autoEscape(opts.prefix, opts);
if (opts.groupSeparator !== "") {
if (opts.definitions[opts.groupSeparator] === undefined) {
//update separatot definition
opts.definitions[opts.groupSeparator] = {};
opts.definitions[opts.groupSeparator].validator = "[" + opts.groupSeparator + "]";
opts.definitions[opts.groupSeparator].placeholder = opts.groupSeparator;
opts.definitions[opts.groupSeparator].static = true;
opts.definitions[opts.groupSeparator].generated = true; //forced marker as generated input
}
mask += opts._mask(opts);
} else {
mask += "9{+}";
}
if (opts.digits !== undefined && opts.digits !== 0) {
var dq = opts.digits.toString().split(",");
if (isFinite(dq[0]) && dq[1] && isFinite(dq[1])) {
mask += radixPointDef + decimalDef + "{" + opts.digits + "}";
} else if (isNaN(opts.digits) || parseInt(opts.digits) > 0) {
if (opts.digitsOptional || opts.jitMasking) {
altMask = mask + radixPointDef + decimalDef + "{0," + opts.digits + "}";
// mask += "[" + opts.radixPoint + "]";
opts.keepStatic = true;
} else {
mask += radixPointDef + decimalDef + "{" + opts.digits + "}";
}
}
} else {
opts.inputmode = "numeric";
}
mask += autoEscape(opts.suffix, opts);
mask += "[-]";
var mask = "[+]", altMask;
mask += autoEscape(opts.prefix, opts);
if (opts.groupSeparator !== "") {
if (opts.definitions[opts.groupSeparator] === undefined) {
//update separatot definition
opts.definitions[opts.groupSeparator] = {};
opts.definitions[opts.groupSeparator].validator = "[" + opts.groupSeparator + "]";
opts.definitions[opts.groupSeparator].placeholder = opts.groupSeparator;
opts.definitions[opts.groupSeparator].static = true;
opts.definitions[opts.groupSeparator].generated = true; //forced marker as generated input
}
mask += opts._mask(opts);
} else {
mask += "9{+}";
}
if (opts.digits !== undefined && opts.digits !== 0) {
var dq = opts.digits.toString().split(",");
if (isFinite(dq[0]) && dq[1] && isFinite(dq[1])) {
mask += radixPointDef + decimalDef + "{" + opts.digits + "}";
} else if (isNaN(opts.digits) || parseInt(opts.digits) > 0) {
if (opts.digitsOptional || opts.jitMasking) {
altMask = mask + radixPointDef + decimalDef + "{0," + opts.digits + "}";
// mask += "[" + opts.radixPoint + "]";
opts.keepStatic = true;
} else {
mask += radixPointDef + decimalDef + "{" + opts.digits + "}";
}
}
} else {
opts.inputmode = "numeric";
}
mask += autoEscape(opts.suffix, opts);
mask += "[-]";
if (altMask) {
mask = [(altMask + autoEscape(opts.suffix, opts) + "[-]"), mask];
}
if (altMask) {
mask = [(altMask + autoEscape(opts.suffix, opts) + "[-]"), mask];
}
opts.greedy = false; //enforce greedy false
opts.greedy = false; //enforce greedy false
parseMinMaxOptions(opts);
if (opts.radixPoint !== "" && opts.substituteRadixPoint)
opts.substitutes[opts.radixPoint == "." ? "," : "."] = opts.radixPoint;
// console.log(mask);
return mask;
parseMinMaxOptions(opts);
if (opts.radixPoint !== "" && opts.substituteRadixPoint)
opts.substitutes[opts.radixPoint == "." ? "," : "."] = opts.radixPoint;
// console.log(mask);
return mask;
}
function hanndleRadixDance(pos, c, radixPos, maskset, opts) {
if (opts._radixDance && opts.numericInput && c !== opts.negationSymbol.back) {
if (pos <= radixPos && (radixPos > 0 || c == opts.radixPoint) && (maskset.validPositions[pos - 1] === undefined || maskset.validPositions[pos - 1].input !== opts.negationSymbol.back)) {
pos -= 1;
}
}
return pos;
if (opts._radixDance && opts.numericInput && c !== opts.negationSymbol.back) {
if (pos <= radixPos && (radixPos > 0 || c == opts.radixPoint) && (maskset.validPositions[pos - 1] === undefined || maskset.validPositions[pos - 1].input !== opts.negationSymbol.back)) {
pos -= 1;
}
}
return pos;
}
function decimalValidator(chrs, maskset, pos, strict, opts) {
var radixPos = maskset.buffer ? maskset.buffer.indexOf(opts.radixPoint) : -1,
result = (radixPos !== -1 || (strict && opts.jitMasking)) && new RegExp(opts.definitions["9"].validator).test(chrs);
if (opts._radixDance && radixPos !== -1 && result && maskset.validPositions[radixPos] == undefined) {
return {
insert: {
pos: radixPos === pos ? radixPos + 1 : radixPos,
c: opts.radixPoint
},
pos: pos
};
}
var radixPos = maskset.buffer ? maskset.buffer.indexOf(opts.radixPoint) : -1,
result = (radixPos !== -1 || (strict && opts.jitMasking)) && new RegExp(opts.definitions["9"].validator).test(chrs);
if (opts._radixDance && radixPos !== -1 && result && maskset.validPositions[radixPos] == undefined) {
return {
insert: {
pos: radixPos === pos ? radixPos + 1 : radixPos,
c: opts.radixPoint
},
pos: pos
};
}
return result;
return result;
}
function checkForLeadingZeroes(buffer, opts) {
//check leading zeros
var numberMatches = new RegExp("(^" + (opts.negationSymbol.front !== "" ? escapeRegex(opts.negationSymbol.front) + "?" : "") + escapeRegex(opts.prefix) + ")(.*)(" + escapeRegex(opts.suffix) + (opts.negationSymbol.back != "" ? escapeRegex(opts.negationSymbol.back) + "?" : "") + "$)").exec(buffer.slice().reverse().join("")),
number = numberMatches ? numberMatches[2] : "", leadingzeroes = false;
if (number) {
number = number.split(opts.radixPoint.charAt(0))[0];
leadingzeroes = new RegExp("^[0" + opts.groupSeparator + "]*").exec(number);
}
return leadingzeroes && (leadingzeroes[0].length > 1 || leadingzeroes[0].length > 0 && leadingzeroes[0].length < number.length) ? leadingzeroes : false;
//check leading zeros
var numberMatches = new RegExp("(^" + (opts.negationSymbol.front !== "" ? escapeRegex(opts.negationSymbol.front) + "?" : "") + escapeRegex(opts.prefix) + ")(.*)(" + escapeRegex(opts.suffix) + (opts.negationSymbol.back != "" ? escapeRegex(opts.negationSymbol.back) + "?" : "") + "$)").exec(buffer.slice().reverse().join("")),
number = numberMatches ? numberMatches[2] : "", leadingzeroes = false;
if (number) {
number = number.split(opts.radixPoint.charAt(0))[0];
leadingzeroes = new RegExp("^[0" + opts.groupSeparator + "]*").exec(number);
}
return leadingzeroes && (leadingzeroes[0].length > 1 || leadingzeroes[0].length > 0 && leadingzeroes[0].length < number.length) ? leadingzeroes : false;
}

@@ -242,406 +241,406 @@

Inputmask.extendAliases({
"numeric": {
mask: genMask,
_mask: function (opts) {
return "(" + opts.groupSeparator + "999){+|1}";
},
digits: "*", //number of fractionalDigits
digitsOptional: true,
enforceDigitsOnBlur: false,
radixPoint: ".",
positionCaretOnClick: "radixFocus",
_radixDance: true,
groupSeparator: "",
allowMinus: true,
negationSymbol: {
front: "-", //"("
back: "" //")"
},
prefix: "",
suffix: "",
min: null, //minimum value
max: null, //maximum value
SetMaxOnOverflow: false,
step: 1,
inputType: "text", //number ~ specify that values which are set are in textform (radix point is same as in the options) or in numberform (radixpoint = .)
unmaskAsNumber: false,
roundingFN: Math.round, //Math.floor , fn(x)
inputmode: "decimal",
shortcuts: {k: "1000", m: "1000000"},
//global options
placeholder: "0",
greedy: false,
rightAlign: true,
insertMode: true,
autoUnmask: false,
skipOptionalPartCharacter: "",
usePrototypeDefinitions: false,
stripLeadingZeroes: true,
substituteRadixPoint: true,
definitions: {
"0": {
validator: decimalValidator
},
"1": {
validator: decimalValidator,
definitionSymbol: "9"
},
"9": { //\uFF11-\uFF19 #1606
validator: "[0-9\uFF10-\uFF19\u0660-\u0669\u06F0-\u06F9]",
definitionSymbol: "*"
},
"+": {
validator: function (chrs, maskset, pos, strict, opts) {
return (opts.allowMinus && (chrs === "-" || chrs === opts.negationSymbol.front));
"numeric": {
mask: genMask,
_mask: function (opts) {
return "(" + opts.groupSeparator + "999){+|1}";
},
digits: "*", //number of fractionalDigits
digitsOptional: true,
enforceDigitsOnBlur: false,
radixPoint: ".",
positionCaretOnClick: "radixFocus",
_radixDance: true,
groupSeparator: "",
allowMinus: true,
negationSymbol: {
front: "-", //"("
back: "" //")"
},
prefix: "",
suffix: "",
min: null, //minimum value
max: null, //maximum value
SetMaxOnOverflow: false,
step: 1,
inputType: "text", //number ~ specify that values which are set are in textform (radix point is same as in the options) or in numberform (radixpoint = .)
unmaskAsNumber: false,
roundingFN: Math.round, //Math.floor , fn(x)
inputmode: "decimal",
shortcuts: {k: "1000", m: "1000000"},
//global options
placeholder: "0",
greedy: false,
rightAlign: true,
insertMode: true,
autoUnmask: false,
skipOptionalPartCharacter: "",
usePrototypeDefinitions: false,
stripLeadingZeroes: true,
substituteRadixPoint: true,
definitions: {
"0": {
validator: decimalValidator
},
"1": {
validator: decimalValidator,
definitionSymbol: "9"
},
"9": { //\uFF11-\uFF19 #1606
validator: "[0-9\uFF10-\uFF19\u0660-\u0669\u06F0-\u06F9]",
definitionSymbol: "*"
},
"+": {
validator: function (chrs, maskset, pos, strict, opts) {
return (opts.allowMinus && (chrs === "-" || chrs === opts.negationSymbol.front));
}
},
"-": {
validator: function (chrs, maskset, pos, strict, opts) {
return (opts.allowMinus && chrs === opts.negationSymbol.back);
}
}
},
preValidation: function (buffer, pos, c, isSelection, opts, maskset, caretPos, strict) {
const inputmask = this;
}
},
"-": {
validator: function (chrs, maskset, pos, strict, opts) {
return (opts.allowMinus && chrs === opts.negationSymbol.back);
}
}
},
preValidation: function (buffer, pos, c, isSelection, opts, maskset, caretPos, strict) {
const inputmask = this;
if (opts.__financeInput !== false && c === opts.radixPoint) return false;
var radixPos = buffer.indexOf(opts.radixPoint), initPos = pos;
pos = hanndleRadixDance(pos, c, radixPos, maskset, opts);
if (c === "-" || c === opts.negationSymbol.front) {
if (opts.allowMinus !== true) return false;
var isNegative = false,
front = findValid("+", maskset), back = findValid("-", maskset);
if (front !== -1) {
isNegative = [front, back];
}
if (opts.__financeInput !== false && c === opts.radixPoint) return false;
var radixPos = buffer.indexOf(opts.radixPoint), initPos = pos;
pos = hanndleRadixDance(pos, c, radixPos, maskset, opts);
if (c === "-" || c === opts.negationSymbol.front) {
if (opts.allowMinus !== true) return false;
var isNegative = false,
front = findValid("+", maskset), back = findValid("-", maskset);
if (front !== -1) {
isNegative = [front, back];
}
return isNegative !== false ? {
remove: isNegative,
caret: initPos - opts.negationSymbol.back.length
} : {
insert: [
{
pos: findValidator.call(inputmask, "+", maskset),
c: opts.negationSymbol.front,
fromIsValid: true
},
{
pos: findValidator.call(inputmask, "-", maskset),
c: opts.negationSymbol.back,
fromIsValid: undefined
}],
caret: initPos + opts.negationSymbol.back.length
};
}
return isNegative !== false ? {
remove: isNegative,
caret: initPos - opts.negationSymbol.back.length
} : {
insert: [
{
pos: findValidator.call(inputmask, "+", maskset),
c: opts.negationSymbol.front,
fromIsValid: true
},
{
pos: findValidator.call(inputmask, "-", maskset),
c: opts.negationSymbol.back,
fromIsValid: undefined
}],
caret: initPos + opts.negationSymbol.back.length
};
}
if (c === opts.groupSeparator) {
return {caret: initPos};
}
if (c === opts.groupSeparator) {
return {caret: initPos};
}
if (strict) return true;
if (radixPos !== -1 && (opts._radixDance === true && isSelection === false && c === opts.radixPoint && (opts.digits !== undefined && (isNaN(opts.digits) || parseInt(opts.digits) > 0)) && radixPos !== pos)) {
return {
"caret": opts._radixDance && pos === radixPos - 1 ? radixPos + 1 : radixPos
};
}
if (opts.__financeInput === false) {
if (isSelection) {
if (opts.digitsOptional) {
return {rewritePosition: caretPos.end};
} else if (!opts.digitsOptional) {
if (caretPos.begin > radixPos && caretPos.end <= radixPos) {
if (c === opts.radixPoint) {
return {
insert: {pos: radixPos + 1, c: "0", fromIsValid: true},
rewritePosition: radixPos
};
} else {
return {rewritePosition: radixPos + 1};
}
} else if (caretPos.begin < radixPos) {
return {rewritePosition: caretPos.begin - 1};
}
}
} else if (!opts.showMaskOnHover && !opts.showMaskOnFocus && !opts.digitsOptional && opts.digits > 0 && this.__valueGet.call(this.el) === "") {
return {rewritePosition: radixPos};
}
}
return {rewritePosition: pos};
},
postValidation: function (buffer, pos, c, currentResult, opts, maskset, strict) {
if (currentResult === false) return currentResult;
if (strict) return true;
if (opts.min !== null || opts.max !== null) {
var unmasked = opts.onUnMask(buffer.slice().reverse().join(""), undefined, $.extend({}, opts, {
unmaskAsNumber: true
}));
if (opts.min !== null && unmasked < opts.min && (unmasked.toString().length > opts.min.toString().length || unmasked < 0)) {
return false;
// return {
// refreshFromBuffer: true,
// buffer: alignDigits(opts.min.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
// };
}
if (strict) return true;
if (radixPos !== -1 && (opts._radixDance === true && isSelection === false && c === opts.radixPoint && (opts.digits !== undefined && (isNaN(opts.digits) || parseInt(opts.digits) > 0)) && radixPos !== pos)) {
return {
"caret": opts._radixDance && pos === radixPos - 1 ? radixPos + 1 : radixPos
};
}
if (opts.__financeInput === false) {
if (isSelection) {
if (opts.digitsOptional) {
return {rewritePosition: caretPos.end};
} else if (!opts.digitsOptional) {
if (caretPos.begin > radixPos && caretPos.end <= radixPos) {
if (c === opts.radixPoint) {
return {
insert: {pos: radixPos + 1, c: "0", fromIsValid: true},
rewritePosition: radixPos
};
} else {
return {rewritePosition: radixPos + 1};
}
} else if (caretPos.begin < radixPos) {
return {rewritePosition: caretPos.begin - 1};
}
}
} else if (!opts.showMaskOnHover && !opts.showMaskOnFocus && !opts.digitsOptional && opts.digits > 0 && this.__valueGet.call(this.el) === "") {
return {rewritePosition: radixPos};
}
}
return {rewritePosition: pos};
},
postValidation: function (buffer, pos, c, currentResult, opts, maskset, strict) {
if (currentResult === false) return currentResult;
if (strict) return true;
if (opts.min !== null || opts.max !== null) {
var unmasked = opts.onUnMask(buffer.slice().reverse().join(""), undefined, $.extend({}, opts, {
unmaskAsNumber: true
}));
if (opts.min !== null && unmasked < opts.min && (unmasked.toString().length > opts.min.toString().length || unmasked < 0)) {
return false;
// return {
// refreshFromBuffer: true,
// buffer: alignDigits(opts.min.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
// };
}
if (opts.max !== null && unmasked > opts.max) {
return opts.SetMaxOnOverflow ? {
refreshFromBuffer: true,
buffer: alignDigits(opts.max.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
} : false;
}
}
if (opts.max !== null && unmasked > opts.max) {
return opts.SetMaxOnOverflow ? {
refreshFromBuffer: true,
buffer: alignDigits(opts.max.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
} : false;
}
}
return currentResult;
},
onUnMask: function (maskedValue, unmaskedValue, opts) {
if (unmaskedValue === "" && opts.nullable === true) {
return unmaskedValue;
}
var processValue = maskedValue.replace(opts.prefix, "");
processValue = processValue.replace(opts.suffix, "");
processValue = processValue.replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
if (opts.placeholder.charAt(0) !== "") {
processValue = processValue.replace(new RegExp(opts.placeholder.charAt(0), "g"), "0");
}
if (opts.unmaskAsNumber) {
if (opts.radixPoint !== "" && processValue.indexOf(opts.radixPoint) !== -1) processValue = processValue.replace(escapeRegex.call(this, opts.radixPoint), ".");
processValue = processValue.replace(new RegExp("^" + escapeRegex(opts.negationSymbol.front)), "-");
processValue = processValue.replace(new RegExp(escapeRegex(opts.negationSymbol.back) + "$"), "");
return Number(processValue);
}
return processValue;
}
,
isComplete: function (buffer, opts) {
var maskedValue = (opts.numericInput ? buffer.slice().reverse() : buffer).join("");
maskedValue = maskedValue.replace(new RegExp("^" + escapeRegex(opts.negationSymbol.front)), "-");
maskedValue = maskedValue.replace(new RegExp(escapeRegex(opts.negationSymbol.back) + "$"), "");
maskedValue = maskedValue.replace(opts.prefix, "");
maskedValue = maskedValue.replace(opts.suffix, "");
maskedValue = maskedValue.replace(new RegExp(escapeRegex(opts.groupSeparator) + "([0-9]{3})", "g"), "$1");
if (opts.radixPoint === ",") maskedValue = maskedValue.replace(escapeRegex(opts.radixPoint), ".");
return isFinite(maskedValue);
},
onBeforeMask: function (initialValue, opts) {
var radixPoint = opts.radixPoint || ",";
if (isFinite(opts.digits)) opts.digits = parseInt(opts.digits);
return currentResult;
},
onUnMask: function (maskedValue, unmaskedValue, opts) {
if (unmaskedValue === "" && opts.nullable === true) {
return unmaskedValue;
}
var processValue = maskedValue.replace(opts.prefix, "");
processValue = processValue.replace(opts.suffix, "");
processValue = processValue.replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
if (opts.placeholder.charAt(0) !== "") {
processValue = processValue.replace(new RegExp(opts.placeholder.charAt(0), "g"), "0");
}
if (opts.unmaskAsNumber) {
if (opts.radixPoint !== "" && processValue.indexOf(opts.radixPoint) !== -1) processValue = processValue.replace(escapeRegex.call(this, opts.radixPoint), ".");
processValue = processValue.replace(new RegExp("^" + escapeRegex(opts.negationSymbol.front)), "-");
processValue = processValue.replace(new RegExp(escapeRegex(opts.negationSymbol.back) + "$"), "");
return Number(processValue);
}
return processValue;
}
,
isComplete: function (buffer, opts) {
var maskedValue = (opts.numericInput ? buffer.slice().reverse() : buffer).join("");
maskedValue = maskedValue.replace(new RegExp("^" + escapeRegex(opts.negationSymbol.front)), "-");
maskedValue = maskedValue.replace(new RegExp(escapeRegex(opts.negationSymbol.back) + "$"), "");
maskedValue = maskedValue.replace(opts.prefix, "");
maskedValue = maskedValue.replace(opts.suffix, "");
maskedValue = maskedValue.replace(new RegExp(escapeRegex(opts.groupSeparator) + "([0-9]{3})", "g"), "$1");
if (opts.radixPoint === ",") maskedValue = maskedValue.replace(escapeRegex(opts.radixPoint), ".");
return isFinite(maskedValue);
},
onBeforeMask: function (initialValue, opts) {
var radixPoint = opts.radixPoint || ",";
if (isFinite(opts.digits)) opts.digits = parseInt(opts.digits);
if ((typeof initialValue == "number" || opts.inputType === "number") && radixPoint !== "") {
initialValue = initialValue.toString().replace(".", radixPoint);
}
var isNagtive = initialValue.charAt(0) === "-" || initialValue.charAt(0) === opts.negationSymbol.front;
var valueParts = initialValue.split(radixPoint),
integerPart = valueParts[0].replace(/[^\-0-9]/g, ""),
decimalPart = valueParts.length > 1 ? valueParts[1].replace(/[^0-9]/g, "") : "",
forceDigits = valueParts.length > 1;
if ((typeof initialValue == "number" || opts.inputType === "number") && radixPoint !== "") {
initialValue = initialValue.toString().replace(".", radixPoint);
}
var isNagtive = initialValue.charAt(0) === "-" || initialValue.charAt(0) === opts.negationSymbol.front;
var valueParts = initialValue.split(radixPoint),
integerPart = valueParts[0].replace(/[^\-0-9]/g, ""),
decimalPart = valueParts.length > 1 ? valueParts[1].replace(/[^0-9]/g, "") : "",
forceDigits = valueParts.length > 1;
initialValue = integerPart + (decimalPart !== "" ? radixPoint + decimalPart : decimalPart);
initialValue = integerPart + (decimalPart !== "" ? radixPoint + decimalPart : decimalPart);
var digits = 0;
if (radixPoint !== "") {
digits = !opts.digitsOptional ? opts.digits : (opts.digits < decimalPart.length ? opts.digits : decimalPart.length);
if (decimalPart !== "" || !opts.digitsOptional) {
var digitsFactor = Math.pow(10, digits || 1);
var digits = 0;
if (radixPoint !== "") {
digits = !opts.digitsOptional ? opts.digits : (opts.digits < decimalPart.length ? opts.digits : decimalPart.length);
if (decimalPart !== "" || !opts.digitsOptional) {
var digitsFactor = Math.pow(10, digits || 1);
//make the initialValue a valid javascript number for the parsefloat
initialValue = initialValue.replace(escapeRegex(radixPoint), ".");
if (!isNaN(parseFloat(initialValue))) {
initialValue = (opts.roundingFN(parseFloat(initialValue) * digitsFactor) / digitsFactor).toFixed(digits);
}
initialValue = initialValue.toString().replace(".", radixPoint);
}
}
//this needs to be in a separate part and not directly in decimalPart to allow rounding
if (opts.digits === 0 && initialValue.indexOf(radixPoint) !== -1) {
initialValue = initialValue.substring(0, initialValue.indexOf(radixPoint));
}
//make the initialValue a valid javascript number for the parsefloat
initialValue = initialValue.replace(escapeRegex(radixPoint), ".");
if (!isNaN(parseFloat(initialValue))) {
initialValue = (opts.roundingFN(parseFloat(initialValue) * digitsFactor) / digitsFactor).toFixed(digits);
}
initialValue = initialValue.toString().replace(".", radixPoint);
}
}
//this needs to be in a separate part and not directly in decimalPart to allow rounding
if (opts.digits === 0 && initialValue.indexOf(radixPoint) !== -1) {
initialValue = initialValue.substring(0, initialValue.indexOf(radixPoint));
}
if (opts.min !== null || opts.max !== null) {
var numberValue = initialValue.toString().replace(radixPoint, ".");
if (opts.min !== null && numberValue < opts.min) {
initialValue = opts.min.toString().replace(".", radixPoint);
} else if (opts.max !== null && numberValue > opts.max) {
initialValue = opts.max.toString().replace(".", radixPoint);
}
}
if (opts.min !== null || opts.max !== null) {
var numberValue = initialValue.toString().replace(radixPoint, ".");
if (opts.min !== null && numberValue < opts.min) {
initialValue = opts.min.toString().replace(".", radixPoint);
} else if (opts.max !== null && numberValue > opts.max) {
initialValue = opts.max.toString().replace(".", radixPoint);
}
}
if (isNagtive && initialValue.charAt(0) !== "-") {
initialValue = "-" + initialValue;
}
return alignDigits(initialValue.toString().split(""), digits, opts, forceDigits).join("");
}
,
onBeforeWrite: function (e, buffer, caretPos, opts) {
function stripBuffer(buffer, stripRadix) {
if (opts.__financeInput !== false || stripRadix) {
var position = buffer.indexOf(opts.radixPoint);
if (position !== -1) {
buffer.splice(position, 1);
}
}
if (opts.groupSeparator !== "") {
while ((position = buffer.indexOf(opts.groupSeparator)) !== -1) {
buffer.splice(position, 1);
}
}
if (isNagtive && initialValue.charAt(0) !== "-") {
initialValue = "-" + initialValue;
}
return alignDigits(initialValue.toString().split(""), digits, opts, forceDigits).join("");
}
,
onBeforeWrite: function (e, buffer, caretPos, opts) {
function stripBuffer(buffer, stripRadix) {
if (opts.__financeInput !== false || stripRadix) {
var position = buffer.indexOf(opts.radixPoint);
if (position !== -1) {
buffer.splice(position, 1);
}
}
if (opts.groupSeparator !== "") {
while ((position = buffer.indexOf(opts.groupSeparator)) !== -1) {
buffer.splice(position, 1);
}
}
return buffer;
}
return buffer;
}
let result, leadingzeroes;
if (opts.stripLeadingZeroes && (leadingzeroes = checkForLeadingZeroes(buffer, opts))) {
const caretNdx = buffer.join("").lastIndexOf(leadingzeroes[0].split("").reverse().join("")) - (leadingzeroes[0] == leadingzeroes.input ? 0 : 1),
offset = (leadingzeroes[0] == leadingzeroes.input ? 1 : 0);
for (let i = leadingzeroes[0].length - offset; i > 0; i--) {
delete this.maskset.validPositions[caretNdx + i];
delete buffer[caretNdx + i];
}
}
let result, leadingzeroes;
if (opts.stripLeadingZeroes && (leadingzeroes = checkForLeadingZeroes(buffer, opts))) {
const caretNdx = buffer.join("").lastIndexOf(leadingzeroes[0].split("").reverse().join("")) - (leadingzeroes[0] == leadingzeroes.input ? 0 : 1),
offset = (leadingzeroes[0] == leadingzeroes.input ? 1 : 0);
for (let i = leadingzeroes[0].length - offset; i > 0; i--) {
delete this.maskset.validPositions[caretNdx + i];
delete buffer[caretNdx + i];
}
}
if (e) {
switch (e.type) {
case "blur":
case "checkval":
if (opts.min !== null) {
var unmasked = opts.onUnMask(buffer.slice().reverse().join(""), undefined, $.extend({}, opts, {
unmaskAsNumber: true
}));
if (opts.min !== null && unmasked < opts.min) {
return {
refreshFromBuffer: true,
buffer: alignDigits(opts.min.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
};
}
}
if (buffer[buffer.length - 1] === opts.negationSymbol.front) { //strip negation symbol on blur when value is 0
var nmbrMtchs = new RegExp("(^" + (opts.negationSymbol.front != "" ? escapeRegex(opts.negationSymbol.front) + "?" : "") + escapeRegex(opts.prefix) + ")(.*)(" + escapeRegex(opts.suffix) + (opts.negationSymbol.back != "" ? escapeRegex(opts.negationSymbol.back) + "?" : "") + "$)").exec(stripBuffer(buffer.slice(), true).reverse().join("")),
number = nmbrMtchs ? nmbrMtchs[2] : "";
if (number == 0) {
result = {refreshFromBuffer: true, buffer: [0]};
}
} else if (opts.radixPoint !== "") { //strip radixpoint on blur when it is the latest char
var radixNDX = buffer.indexOf(opts.radixPoint);
if (radixNDX === opts.suffix.length) {
if (result && result.buffer) {
result.buffer.splice(0, 1 + opts.suffix.length);
} else {
buffer.splice(0, 1 + opts.suffix.length);
result =
{refreshFromBuffer: true, buffer: stripBuffer(buffer)};
}
}
}
if (e) {
switch (e.type) {
case "blur":
case "checkval":
if (opts.min !== null) {
var unmasked = opts.onUnMask(buffer.slice().reverse().join(""), undefined, $.extend({}, opts, {
unmaskAsNumber: true
}));
if (opts.min !== null && unmasked < opts.min) {
return {
refreshFromBuffer: true,
buffer: alignDigits(opts.min.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
};
}
}
if (buffer[buffer.length - 1] === opts.negationSymbol.front) { //strip negation symbol on blur when value is 0
var nmbrMtchs = new RegExp("(^" + (opts.negationSymbol.front != "" ? escapeRegex(opts.negationSymbol.front) + "?" : "") + escapeRegex(opts.prefix) + ")(.*)(" + escapeRegex(opts.suffix) + (opts.negationSymbol.back != "" ? escapeRegex(opts.negationSymbol.back) + "?" : "") + "$)").exec(stripBuffer(buffer.slice(), true).reverse().join("")),
number = nmbrMtchs ? nmbrMtchs[2] : "";
if (number == 0) {
result = {refreshFromBuffer: true, buffer: [0]};
}
} else if (opts.radixPoint !== "") { //strip radixpoint on blur when it is the latest char
var radixNDX = buffer.indexOf(opts.radixPoint);
if (radixNDX === opts.suffix.length) {
if (result && result.buffer) {
result.buffer.splice(0, 1 + opts.suffix.length);
} else {
buffer.splice(0, 1 + opts.suffix.length);
result =
{refreshFromBuffer: true, buffer: stripBuffer(buffer)};
}
}
}
if (opts.enforceDigitsOnBlur) {
result = result || {};
var bffr = (result && result.buffer) || buffer.slice().reverse();
result.refreshFromBuffer = true;
result.buffer = alignDigits(bffr, opts.digits, opts, true).reverse();
}
}
}
if (opts.enforceDigitsOnBlur) {
result = result || {};
var bffr = (result && result.buffer) || buffer.slice().reverse();
result.refreshFromBuffer = true;
result.buffer = alignDigits(bffr, opts.digits, opts, true).reverse();
}
}
}
return result;
},
onKeyDown: function (e, buffer, caretPos, opts) {
var $input = $(this), bffr;
if (e.location != 3) {
var pattern, c = String.fromCharCode(e.keyCode).toLowerCase();
if ((pattern = (opts.shortcuts && opts.shortcuts[c]))) {
if (pattern.length > 1) {
this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) * parseInt(pattern));
$input.trigger("setvalue");
return false;
}
}
}
if (e.ctrlKey) {
switch (e.keyCode) {
case keyCode.UP:
this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) + parseInt(opts.step));
$input.trigger("setvalue");
return false;
case keyCode.DOWN:
this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) - parseInt(opts.step));
$input.trigger("setvalue");
return false;
}
}
if (!e.shiftKey && (e.keyCode === keyCode.DELETE || e.keyCode === keyCode.BACKSPACE || e.keyCode === keyCode.BACKSPACE_SAFARI) && caretPos.begin !== buffer.length) {
if (buffer[e.keyCode === keyCode.DELETE ? caretPos.begin - 1 : caretPos.end] === opts.negationSymbol.front) {
bffr = buffer.slice().reverse();
if (opts.negationSymbol.front !== "") bffr.shift();
if (opts.negationSymbol.back !== "") bffr.pop();
$input.trigger("setvalue", [bffr.join(""), caretPos.begin]);
return false;
} else if (opts._radixDance === true) {
var radixPos = buffer.indexOf(opts.radixPoint);
if (!opts.digitsOptional) {
if (radixPos !== -1 && (caretPos.begin < radixPos || caretPos.end < radixPos || (e.keyCode === keyCode.DELETE && (caretPos.begin === radixPos || caretPos.begin - 1 === radixPos)))) {
var restoreCaretPos = undefined;
if (caretPos.begin === caretPos.end) { //only adjust when not a selection
if (e.keyCode === keyCode.BACKSPACE || e.keyCode === keyCode.BACKSPACE_SAFARI)
caretPos.begin++;
else if (e.keyCode === keyCode.DELETE && caretPos.begin - 1 === radixPos) {
restoreCaretPos = $.extend({}, caretPos);
caretPos.begin--;
caretPos.end--;
return result;
},
onKeyDown: function (e, buffer, caretPos, opts) {
var $input = $(this), bffr;
if (e.location != 3) {
var pattern, c = String.fromCharCode(e.keyCode).toLowerCase();
if ((pattern = (opts.shortcuts && opts.shortcuts[c]))) {
if (pattern.length > 1) {
this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) * parseInt(pattern));
$input.trigger("setvalue");
return false;
}
}
}
if (e.ctrlKey) {
switch (e.keyCode) {
case keyCode.UP:
this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) + parseInt(opts.step));
$input.trigger("setvalue");
return false;
case keyCode.DOWN:
this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) - parseInt(opts.step));
$input.trigger("setvalue");
return false;
}
}
if (!e.shiftKey && (e.keyCode === keyCode.DELETE || e.keyCode === keyCode.BACKSPACE || e.keyCode === keyCode.BACKSPACE_SAFARI) && caretPos.begin !== buffer.length) {
if (buffer[e.keyCode === keyCode.DELETE ? caretPos.begin - 1 : caretPos.end] === opts.negationSymbol.front) {
bffr = buffer.slice().reverse();
if (opts.negationSymbol.front !== "") bffr.shift();
if (opts.negationSymbol.back !== "") bffr.pop();
$input.trigger("setvalue", [bffr.join(""), caretPos.begin]);
return false;
} else if (opts._radixDance === true) {
var radixPos = buffer.indexOf(opts.radixPoint);
if (!opts.digitsOptional) {
if (radixPos !== -1 && (caretPos.begin < radixPos || caretPos.end < radixPos || (e.keyCode === keyCode.DELETE && (caretPos.begin === radixPos || caretPos.begin - 1 === radixPos)))) {
var restoreCaretPos = undefined;
if (caretPos.begin === caretPos.end) { //only adjust when not a selection
if (e.keyCode === keyCode.BACKSPACE || e.keyCode === keyCode.BACKSPACE_SAFARI)
caretPos.begin++;
else if (e.keyCode === keyCode.DELETE && caretPos.begin - 1 === radixPos) {
restoreCaretPos = $.extend({}, caretPos);
caretPos.begin--;
caretPos.end--;
}
}
bffr = buffer.slice().reverse();
bffr.splice(bffr.length - caretPos.begin, caretPos.begin - caretPos.end + 1);
// console.log(caretPos);
bffr = alignDigits(bffr, opts.digits, opts).join("");
if (restoreCaretPos) {
caretPos = restoreCaretPos;
}
$input.trigger("setvalue", [bffr, caretPos.begin >= bffr.length ? radixPos + 1 : caretPos.begin]);
return false;
}
} else if (radixPos === 0) {
bffr = buffer.slice().reverse();
bffr.pop();
$input.trigger("setvalue", [bffr.join(""), caretPos.begin >= bffr.length ? bffr.length : caretPos.begin]);
return false;
}
}
}
}
},
"currency": {
prefix: "", //"$ ",
groupSeparator: ",",
alias: "numeric",
digits: 2,
digitsOptional: false
},
"decimal": {
alias: "numeric"
},
"integer": {
alias: "numeric",
inputmode: "numeric",
digits: 0
},
"percentage": {
alias: "numeric",
min: 0,
max: 100,
suffix: " %",
digits: 0,
allowMinus: false
},
"indianns": { //indian numbering system
alias: "numeric",
_mask: function (opts) {
return "(" + opts.groupSeparator + "99){*|1}(" + opts.groupSeparator + "999){1|1}";
},
groupSeparator: ",",
radixPoint: ".",
placeholder: "0",
digits: 2,
digitsOptional: false
}
}
}
bffr = buffer.slice().reverse();
bffr.splice(bffr.length - caretPos.begin, caretPos.begin - caretPos.end + 1);
// console.log(caretPos);
bffr = alignDigits(bffr, opts.digits, opts).join("");
if (restoreCaretPos) {
caretPos = restoreCaretPos;
}
$input.trigger("setvalue", [bffr, caretPos.begin >= bffr.length ? radixPos + 1 : caretPos.begin]);
return false;
}
} else if (radixPos === 0) {
bffr = buffer.slice().reverse();
bffr.pop();
$input.trigger("setvalue", [bffr.join(""), caretPos.begin >= bffr.length ? bffr.length : caretPos.begin]);
return false;
}
}
}
}
},
"currency": {
prefix: "", //"$ ",
groupSeparator: ",",
alias: "numeric",
digits: 2,
digitsOptional: false
},
"decimal": {
alias: "numeric"
},
"integer": {
alias: "numeric",
inputmode: "numeric",
digits: 0
},
"percentage": {
alias: "numeric",
min: 0,
max: 100,
suffix: " %",
digits: 0,
allowMinus: false
},
"indianns": { //indian numbering system
alias: "numeric",
_mask: function (opts) {
return "(" + opts.groupSeparator + "99){*|1}(" + opts.groupSeparator + "999){1|1}";
},
groupSeparator: ",",
radixPoint: ".",
placeholder: "0",
digits: 2,
digitsOptional: false
}
});

@@ -202,3 +202,3 @@ import keyCode from "./keycode.json";

vps = maskset.validPositions;
for (var pndx in vps) {
for (let pndx = 0, vpl = vps.length; pndx < vpl; pndx++) {
if (vps[pndx] && vps[pndx].match && (vps[pndx].match.static != true || (Array.isArray(maskset.metadata) && vps[pndx].generatedInput !== true))) {

@@ -205,0 +205,0 @@ //only include generated input with multiple masks (check on metadata)

@@ -26,286 +26,286 @@ /*

function Inputmask(alias, options, internal) {
if (!canUseDOM) {
return;
}
//allow instanciating without new
if (!(this instanceof Inputmask)) {
return new Inputmask(alias, options, internal);
}
if (!canUseDOM) {
return;
}
this.dependencyLib = $;
this.el = undefined;
this.events = {};
this.maskset = undefined;
//allow instanciating without new
if (!(this instanceof Inputmask)) {
return new Inputmask(alias, options, internal);
}
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);
}
this.dependencyLib = $;
this.el = undefined;
this.events = {};
this.maskset = undefined;
//maskscope properties
this.refreshValue = false; //indicate a refresh from the inputvalue is needed (form.reset)
this.undoValue = undefined;
this.$el = undefined;
this.skipKeyPressEvent = false; //Safari 5.1.x - modal dialog fires keypress twice workaround
this.skipInputEvent = false; //skip when triggered from within inputmask
this.validationEvent = false;
this.ignorable = false;
this.maxLength;
this.mouseEnter = false;
this.originalPlaceholder = undefined; //needed for FF
this.isComposing = false; //keydowncode == 229 compositionevent fallback
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.skipKeyPressEvent = false; //Safari 5.1.x - modal dialog fires keypress twice workaround
this.skipInputEvent = false; //skip when triggered from within inputmask
this.validationEvent = false;
this.ignorable = false;
this.maxLength;
this.mouseEnter = false;
this.originalPlaceholder = undefined; //needed for FF
this.isComposing = false; //keydowncode == 229 compositionevent fallback
}
Inputmask.prototype = {
dataAttribute: "data-inputmask", //data attribute prefix used for attribute binding
//options default
defaults: defaults,
definitions: definitions,
aliases: {}, //aliases definitions
masksCache: {},
get isRTL() {
return this.opts.isRTL || this.opts.numericInput;
},
mask: function (elems) {
var 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) {
var scopedOpts = $.extend(true, {}, that.opts);
if (importAttributeOptions(el, scopedOpts, $.extend(true, {}, that.userOptions), that.dataAttribute)) {
var 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;
dataAttribute: "data-inputmask", //data attribute prefix used for attribute binding
//options default
defaults: defaults,
definitions: definitions,
aliases: {}, //aliases definitions
masksCache: {},
get isRTL() {
return this.opts.isRTL || this.opts.numericInput;
},
mask: function (elems) {
var 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) {
var scopedOpts = $.extend(true, {}, that.opts);
if (importAttributeOptions(el, scopedOpts, $.extend(true, {}, that.userOptions), that.dataAttribute)) {
var 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) {
var 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
var 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);
$.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) {
var 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
var 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
var 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 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)) {
var maskTarget = getMaskTemplate.call(this, true, 0, false).join("");
this.maskset.metadata.forEach(function (mtdt) {
if (mtdt.mask === maskTarget) {
maskTarget = mtdt;
return false;
}
//restore the value property
var 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)) {
var 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) {
var 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("");
}
var buffer = getBuffer.call(this);
var 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 true;
});
return maskTarget;
}
return this.maskset.metadata;
},
isValid: function (value) {
this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
if (value) {
var 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("");
}
var buffer = getBuffer.call(this);
var 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(""));
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);
let valueBuffer = (typeof this.opts.onBeforeMask === "function" ? (this.opts.onBeforeMask.call(this, value, this.opts) || value) : value).split("");
checkVal.call(this, undefined, true, false, valueBuffer);
let 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: analyseMask
},
format: function (value, metadata) {
this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
let valueBuffer = (typeof this.opts.onBeforeMask === "function" ? (this.opts.onBeforeMask.call(this, value, this.opts) || value) : value).split("");
checkVal.call(this, undefined, true, false, valueBuffer);
let 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: analyseMask
};
function resolveAlias(aliasStr, options, opts) {
var 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;
} else //alias not found - try as mask
if (opts.mask === null) {
opts.mask = aliasStr;
}
var 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;
} else //alias not found - try as mask
if (opts.mask === null) {
opts.mask = aliasStr;
}
return false;
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;
}
}
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) {
var attrOptions = npt.getAttribute(dataAttribute), option, dataoptions, optionData, p;
if (opts.importDataAttributes === true) {
var attrOptions = npt.getAttribute(dataAttribute), option, dataoptions, optionData, p;
if (attrOptions && attrOptions !== "") {
attrOptions = attrOptions.replace(/'/g, "\"");
dataoptions = JSON.parse("{" + attrOptions + "}");
}
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);
}
//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);
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";
}
//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;
}
if (npt.dir === "rtl" || opts.numericInput) {
npt.dir = "ltr";
npt.removeAttribute("dir");
opts.isRTL = true;
}
return Object.keys(userOptions).length;
return Object.keys(userOptions).length;
}

@@ -315,37 +315,37 @@

Inputmask.extendDefaults = function (options) {
$.extend(true, Inputmask.prototype.defaults, options);
$.extend(true, Inputmask.prototype.defaults, options);
};
Inputmask.extendDefinitions = function (definition) {
$.extend(true, Inputmask.prototype.definitions, definition);
$.extend(true, Inputmask.prototype.definitions, definition);
};
Inputmask.extendAliases = function (alias) {
$.extend(true, Inputmask.prototype.aliases, alias);
$.extend(true, Inputmask.prototype.aliases, alias);
};
//static fn on inputmask
Inputmask.format = function (value, options, metadata) {
return Inputmask(options).format(value, metadata);
return Inputmask(options).format(value, metadata);
};
Inputmask.unmask = function (value, options) {
return Inputmask(options).unmaskedvalue(value);
return Inputmask(options).unmaskedvalue(value);
};
Inputmask.isValid = function (value, options) {
return Inputmask(options).isValid(value);
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();
});
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]);
});
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]);
});
};

@@ -352,0 +352,0 @@

import $ from "./dependencyLibs/inputmask.dependencyLib";
import MaskToken from "./masktoken";
import Inputmask from "./inputmask";
import escapeRegex from "./escapeRegex";

@@ -10,2 +11,23 @@ export {generateMaskSet, analyseMask};

function preProcessMask(mask, opts) {
if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
var repeatStart = opts.repeat === "*" ? 0 : (opts.repeat === "+" ? 1 : opts.repeat);
mask = opts.groupmarker[0] + mask + opts.groupmarker[1] + opts.quantifiermarker[0] + repeatStart + "," + opts.repeat + opts.quantifiermarker[1];
}
if (opts.keepStatic === true) {
let optionalRegex = "(?<p1>.)\\[(?<p2>[^\\]]*)\\]",
maskMatches = mask.match(new RegExp(optionalRegex, "g"));
maskMatches && maskMatches.forEach((m, i) => {
let groups = m.split("["), p1 = groups[0], p2 = groups[1].replace("]", "");
mask = mask.replace(new RegExp(`${escapeRegex(p1)}\\[${escapeRegex(p2)}\\]`),
p1.charAt(0) === p2.charAt(0) ?
`(${p1}|${p1}${p2})` :
`${p1}[${p2}]`);
// console.log(mask);
});
}
return mask;
}
function generateMask(mask, metadata, opts) {

@@ -26,6 +48,3 @@ var regexMask = false;

} //hide placeholder with single non-greedy mask
if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
var repeatStart = opts.repeat === "*" ? 0 : (opts.repeat === "+" ? 1 : opts.repeat);
mask = opts.groupmarker[0] + mask + opts.groupmarker[1] + opts.quantifiermarker[0] + repeatStart + "," + opts.repeat + opts.quantifiermarker[1];
}
mask = preProcessMask(mask, opts);

@@ -43,3 +62,3 @@ // console.log(mask);

"maskToken": Inputmask.prototype.analyseMask(mask, regexMask, opts),
"validPositions": {},
"validPositions": [],
"_buffer": undefined,

@@ -46,0 +65,0 @@ "buffer": undefined,

@@ -9,237 +9,241 @@ import keyCode from "./keycode.json";

export{mask};
export {mask};
//todo put on the prototype?
function mask() {
const inputmask = this,
opts= this.opts,
el=this.el,$=this.dependencyLib;
const inputmask = this,
opts = this.opts,
el = this.el, $ = this.dependencyLib;
function isElementTypeSupported(input, opts) {
function patchValueProperty(npt) {
var valueGet;
var valueSet;
function isElementTypeSupported(input, opts) {
function patchValueProperty(npt) {
var valueGet;
var valueSet;
function patchValhook(type) {
if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
return elem.value;
};
var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
elem.value = value;
return elem;
};
function patchValhook(type) {
if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
return elem.value;
};
var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
elem.value = value;
return elem;
};
$.valHooks[type] = {
get: function (elem) {
if (elem.inputmask) {
if (elem.inputmask.opts.autoUnmask) {
return elem.inputmask.unmaskedvalue();
} else {
var result = valhookGet(elem);
return getLastValidPosition.call(inputmask, undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
}
} else {
return valhookGet(elem);
}
},
set: function (elem, value) {
var result = valhookSet(elem, value);
if (elem.inputmask) {
applyInputValue(elem, value);
}
return result;
},
inputmaskpatch: true
};
}
}
$.valHooks[type] = {
get: function (elem) {
if (elem.inputmask) {
if (elem.inputmask.opts.autoUnmask) {
return elem.inputmask.unmaskedvalue();
} else {
var result = valhookGet(elem);
return getLastValidPosition.call(inputmask, undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
}
} else {
return valhookGet(elem);
}
},
set: function (elem, value) {
var result = valhookSet(elem, value);
if (elem.inputmask) {
applyInputValue(elem, value);
}
return result;
},
inputmaskpatch: true
};
}
}
function getter() {
if (this.inputmask) {
return this.inputmask.opts.autoUnmask ?
this.inputmask.unmaskedvalue() :
(getLastValidPosition.call(inputmask) !== -1 || opts.nullable !== true ?
(((this.inputmask.shadowRoot || this.ownerDocument).activeElement) === this && opts.clearMaskOnLostFocus ?
(inputmask.isRTL ? clearOptionalTail.call(inputmask,getBuffer.call(inputmask).slice()).reverse() : clearOptionalTail.call(inputmask,getBuffer.call(inputmask).slice())).join("") :
valueGet.call(this)) :
"");
} else {
return valueGet.call(this);
}
}
function getter() {
if (this.inputmask) {
return this.inputmask.opts.autoUnmask ?
this.inputmask.unmaskedvalue() :
(getLastValidPosition.call(inputmask) !== -1 || opts.nullable !== true ?
(((this.inputmask.shadowRoot || this.ownerDocument).activeElement) === this && opts.clearMaskOnLostFocus ?
(inputmask.isRTL ? clearOptionalTail.call(inputmask, getBuffer.call(inputmask).slice()).reverse() : clearOptionalTail.call(inputmask, getBuffer.call(inputmask).slice())).join("") :
valueGet.call(this)) :
"");
} else {
return valueGet.call(this);
}
}
function setter(value) {
valueSet.call(this, value);
if (this.inputmask) {
applyInputValue(this, value);
}
}
function setter(value) {
valueSet.call(this, value);
if (this.inputmask) {
applyInputValue(this, value);
}
}
function installNativeValueSetFallback(npt) {
EventRuler.on(npt, "mouseenter", function () {
var input = this,
value = input.inputmask._valueGet(true);
if (value !== (inputmask.isRTL ? getBuffer.call(inputmask).reverse() : getBuffer.call(inputmask)).join("")) { //Is this correct? to apply RTL? TOCHECK
applyInputValue(input, value);
}
});
}
function installNativeValueSetFallback(npt) {
EventRuler.on(npt, "mouseenter", function () {
let input = this,
value = input.inputmask._valueGet(true),
bufferValue = (input.inputmask.isRTL ? getBuffer.call(input.inputmask).slice().reverse() : getBuffer.call(input.inputmask)).join("");
if (value != bufferValue) {
applyInputValue(input, value);
}
});
}
if (!npt.inputmask.__valueGet) {
if (opts.noValuePatching !== true) {
if (Object.getOwnPropertyDescriptor) {
var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
if (valueProperty && valueProperty.get && valueProperty.set) {
valueGet = valueProperty.get;
valueSet = valueProperty.set;
Object.defineProperty(npt, "value", {
get: getter,
set: setter,
configurable: true
});
} else if (npt.tagName.toLowerCase() !== "input") {
valueGet = function () {
return this.textContent;
};
valueSet = function (value) {
this.textContent = value;
};
Object.defineProperty(npt, "value", {
get: getter,
set: setter,
configurable: true
});
}
} else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
valueGet = npt.__lookupGetter__("value");
valueSet = npt.__lookupSetter__("value");
if (!npt.inputmask.__valueGet) {
if (opts.noValuePatching !== true) {
if (Object.getOwnPropertyDescriptor) {
var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
if (valueProperty && valueProperty.get && valueProperty.set) {
valueGet = valueProperty.get;
valueSet = valueProperty.set;
Object.defineProperty(npt, "value", {
get: getter,
set: setter,
configurable: true
});
} else if (npt.tagName.toLowerCase() !== "input") {
valueGet = function () {
return this.textContent;
};
valueSet = function (value) {
this.textContent = value;
};
Object.defineProperty(npt, "value", {
get: getter,
set: setter,
configurable: true
});
}
} else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
valueGet = npt.__lookupGetter__("value");
valueSet = npt.__lookupSetter__("value");
npt.__defineGetter__("value", getter);
npt.__defineSetter__("value", setter);
}
npt.inputmask.__valueGet = valueGet; //store native property getter
npt.inputmask.__valueSet = valueSet; //store native property setter
}
npt.inputmask._valueGet = function (overruleRTL) {
return inputmask.isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
};
npt.inputmask._valueSet = function (value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && inputmask.isRTL) ? value.split("").reverse().join("") : value));
};
npt.__defineGetter__("value", getter);
npt.__defineSetter__("value", setter);
}
npt.inputmask.__valueGet = valueGet; //store native property getter
npt.inputmask.__valueSet = valueSet; //store native property setter
}
npt.inputmask._valueGet = function (overruleRTL) {
return inputmask.isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
};
npt.inputmask._valueSet = function (value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && inputmask.isRTL) ? value.split("").reverse().join("") : value));
};
if (valueGet === undefined) { //jquery.val fallback
valueGet = function () {
return this.value;
};
valueSet = function (value) {
this.value = value;
};
patchValhook(npt.type);
installNativeValueSetFallback(npt);
}
}
}
if (valueGet === undefined) { //jquery.val fallback
valueGet = function () {
return this.value;
};
valueSet = function (value) {
this.value = value;
};
patchValhook(npt.type);
installNativeValueSetFallback(npt);
}
}
}
if (input.tagName.toLowerCase() !== "textarea") {
opts.ignorables.push(keyCode.ENTER);
}
if (input.tagName.toLowerCase() !== "textarea") {
opts.ignorables.push(keyCode.ENTER);
}
var elementType = input.getAttribute("type");
var isSupported = (input.tagName.toLowerCase() === "input" && opts.supportsInputType.includes(elementType)) || input.isContentEditable || input.tagName.toLowerCase() === "textarea";
if (!isSupported) {
if (input.tagName.toLowerCase() === "input") {
var el = document.createElement("input");
el.setAttribute("type", elementType);
isSupported = el.type === "text"; //apply mask only if the type is not natively supported
el = null;
} else {
isSupported = "partial";
}
}
if (isSupported !== false) {
patchValueProperty(input);
} else {
input.inputmask = undefined;
}
return isSupported;
}
var elementType = input.getAttribute("type");
var isSupported = (input.tagName.toLowerCase() === "input" && opts.supportsInputType.includes(elementType)) || input.isContentEditable || input.tagName.toLowerCase() === "textarea";
if (!isSupported) {
if (input.tagName.toLowerCase() === "input") {
var el = document.createElement("input");
el.setAttribute("type", elementType);
isSupported = el.type === "text"; //apply mask only if the type is not natively supported
el = null;
} else {
isSupported = "partial";
}
}
if (isSupported !== false) {
patchValueProperty(input);
} else {
input.inputmask = undefined;
}
return isSupported;
}
//unbind all events - to make sure that no other mask will interfere when re-masking
EventRuler.off(el);
var isSupported = isElementTypeSupported(el, opts);
if (isSupported !== false) {
inputmask.originalPlaceholder = el.placeholder;
//unbind all events - to make sure that no other mask will interfere when re-masking
EventRuler.off(el);
var isSupported = isElementTypeSupported(el, opts);
if (isSupported !== false) {
inputmask.originalPlaceholder = el.placeholder;
//read maxlength prop from el
inputmask.maxLength = el !== undefined ? el.maxLength : undefined;
if (inputmask.maxLength === -1) inputmask.maxLength = undefined;
if ("inputMode" in el && el.getAttribute("inputmode") === null) {
el.inputMode = opts.inputmode;
el.setAttribute("inputmode", opts.inputmode);
}
//read maxlength prop from el
inputmask.maxLength = el !== undefined ? el.maxLength : undefined;
if (inputmask.maxLength === -1) inputmask.maxLength = undefined;
if ("inputMode" in el && el.getAttribute("inputmode") === null) {
el.inputMode = opts.inputmode;
el.setAttribute("inputmode", opts.inputmode);
}
if (isSupported === true) {
opts.showMaskOnFocus = opts.showMaskOnFocus && ["cc-number", "cc-exp"].indexOf(el.autocomplete) === -1;
if (iphone) { //selecting the caret shows as a slection on iphone
opts.insertModeVisual = false;
}
if (isSupported === true) {
opts.showMaskOnFocus = opts.showMaskOnFocus && ["cc-number", "cc-exp"].indexOf(el.autocomplete) === -1;
if (iphone) {
//selecting the caret shows as a selection on iphone
opts.insertModeVisual = false;
//disable autocorrect
el.setAttribute("autocorrect", "off");
}
//bind events
EventRuler.on(el, "submit", EventHandlers.submitEvent);
EventRuler.on(el, "reset", EventHandlers.resetEvent);
EventRuler.on(el, "blur", EventHandlers.blurEvent);
EventRuler.on(el, "focus", EventHandlers.focusEvent);
EventRuler.on(el, "invalid", EventHandlers.invalidEvent);
EventRuler.on(el, "click", EventHandlers.clickEvent);
EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
EventRuler.on(el, "paste", EventHandlers.pasteEvent);
EventRuler.on(el, "cut", EventHandlers.cutEvent);
EventRuler.on(el, "complete", opts.oncomplete);
EventRuler.on(el, "incomplete", opts.onincomplete);
EventRuler.on(el, "cleared", opts.oncleared);
if (opts.inputEventOnly !== true) {
EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
EventRuler.on(el, "keyup", EventHandlers.keyupEvent);
}
if (mobile || opts.inputEventOnly) {
el.removeAttribute("maxLength");
}
EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
EventRuler.on(el, "compositionend", EventHandlers.compositionendEvent);
// EventRuler.on(el, "beforeinput", EventHandlers.beforeInputEvent); //https://github.com/w3c/input-events - to implement
}
EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
//bind events
EventRuler.on(el, "submit", EventHandlers.submitEvent);
EventRuler.on(el, "reset", EventHandlers.resetEvent);
EventRuler.on(el, "blur", EventHandlers.blurEvent);
EventRuler.on(el, "focus", EventHandlers.focusEvent);
EventRuler.on(el, "invalid", EventHandlers.invalidEvent);
EventRuler.on(el, "click", EventHandlers.clickEvent);
EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
EventRuler.on(el, "paste", EventHandlers.pasteEvent);
EventRuler.on(el, "cut", EventHandlers.cutEvent);
EventRuler.on(el, "complete", opts.oncomplete);
EventRuler.on(el, "incomplete", opts.onincomplete);
EventRuler.on(el, "cleared", opts.oncleared);
if (opts.inputEventOnly !== true) {
EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
EventRuler.on(el, "keyup", EventHandlers.keyupEvent);
}
if (mobile || opts.inputEventOnly) {
el.removeAttribute("maxLength");
}
EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
EventRuler.on(el, "compositionend", EventHandlers.compositionendEvent);
// EventRuler.on(el, "beforeinput", EventHandlers.beforeInputEvent); //https://github.com/w3c/input-events - to implement
}
EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
//apply mask
getBufferTemplate.call(inputmask).join(""); //initialize the buffer and getmasklength
inputmask.undoValue = inputmask._valueGet(true);
var activeElement = (el.inputmask.shadowRoot || el.ownerDocument).activeElement;
if (el.inputmask._valueGet(true) !== "" || opts.clearMaskOnLostFocus === false || activeElement === el) {
applyInputValue(el, el.inputmask._valueGet(true), opts);
var buffer = getBuffer.call(inputmask).slice();
if (isComplete.call(inputmask, buffer) === false) {
if (opts.clearIncomplete) {
resetMaskSet.call(inputmask);
}
}
if (opts.clearMaskOnLostFocus && activeElement !== el) {
if (getLastValidPosition.call(inputmask) === -1) {
buffer = [];
} else {
clearOptionalTail.call(inputmask, buffer);
}
}
if (opts.clearMaskOnLostFocus === false || (opts.showMaskOnFocus && activeElement === el) || el.inputmask._valueGet(true) !== "") {
writeBuffer(el, buffer);
}
if (activeElement === el) { //position the caret when in focus
caret.call(inputmask,el, seekNext.call(inputmask, getLastValidPosition.call(inputmask)));
}
}
}
//apply mask
getBufferTemplate.call(inputmask).join(""); //initialize the buffer and getmasklength
inputmask.undoValue = inputmask._valueGet(true);
var activeElement = (el.inputmask.shadowRoot || el.ownerDocument).activeElement;
if (el.inputmask._valueGet(true) !== "" || opts.clearMaskOnLostFocus === false || activeElement === el) {
applyInputValue(el, el.inputmask._valueGet(true), opts);
var buffer = getBuffer.call(inputmask).slice();
if (isComplete.call(inputmask, buffer) === false) {
if (opts.clearIncomplete) {
resetMaskSet.call(inputmask);
}
}
if (opts.clearMaskOnLostFocus && activeElement !== el) {
if (getLastValidPosition.call(inputmask) === -1) {
buffer = [];
} else {
clearOptionalTail.call(inputmask, buffer);
}
}
if (opts.clearMaskOnLostFocus === false || (opts.showMaskOnFocus && activeElement === el) || el.inputmask._valueGet(true) !== "") {
writeBuffer(el, buffer);
}
if (activeElement === el) { //position the caret when in focus
caret.call(inputmask, el, seekNext.call(inputmask, getLastValidPosition.call(inputmask)));
}
}
}
}
import {
determineTestTemplate,
getMaskTemplate,
getPlaceholder,
getTest,
getTests,
getTestTemplate
determineTestTemplate,
getMaskTemplate,
getPlaceholder,
getTest,
getTests,
getTestTemplate
} from "./validation-tests";

@@ -12,13 +12,13 @@ import {checkAlternationMatch} from "./validation";

export {
caret,
determineLastRequiredPosition,
determineNewCaretPosition,
getBuffer,
getBufferTemplate,
getLastValidPosition,
isMask,
resetMaskSet,
seekNext,
seekPrevious,
translatePosition
caret,
determineLastRequiredPosition,
determineNewCaretPosition,
getBuffer,
getBufferTemplate,
getLastValidPosition,
isMask,
resetMaskSet,
seekNext,
seekPrevious,
translatePosition
};

@@ -28,81 +28,81 @@

function caret(input, begin, end, notranslate, isDelete) {
const inputmask = this,
opts = this.opts;
const inputmask = this,
opts = this.opts;
var range;
if (begin !== undefined) {
if (Array.isArray(begin)) {
end = inputmask.isRTL ? begin[0] : begin[1];
begin = inputmask.isRTL ? begin[1] : begin[0];
}
if (begin.begin !== undefined) {
end = inputmask.isRTL ? begin.begin : begin.end;
begin = inputmask.isRTL ? begin.end : begin.begin;
}
if (typeof begin === "number") {
begin = notranslate ? begin : translatePosition.call(inputmask, begin);
end = notranslate ? end : translatePosition.call(inputmask, end);
end = (typeof end == "number") ? end : begin;
// if (!$(input).is(":visible")) {
// return;
// }
var range;
if (begin !== undefined) {
if (Array.isArray(begin)) {
end = inputmask.isRTL ? begin[0] : begin[1];
begin = inputmask.isRTL ? begin[1] : begin[0];
}
if (begin.begin !== undefined) {
end = inputmask.isRTL ? begin.begin : begin.end;
begin = inputmask.isRTL ? begin.end : begin.begin;
}
if (typeof begin === "number") {
begin = notranslate ? begin : translatePosition.call(inputmask, begin);
end = notranslate ? end : translatePosition.call(inputmask, end);
end = (typeof end == "number") ? end : begin;
// if (!$(input).is(":visible")) {
// return;
// }
var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
input.inputmask.caretPos = {begin: begin, end: end}; //track caret internally
if (opts.insertModeVisual && opts.insertMode === false && begin === end) {
if (!isDelete) {
end++; //set visualization for insert/overwrite mode
}
}
if (input === (input.inputmask.shadowRoot || input.ownerDocument).activeElement) {
if ("setSelectionRange" in input) {
input.setSelectionRange(begin, end);
} else if (window.getSelection) {
range = document.createRange();
if (input.firstChild === undefined || input.firstChild === null) {
var textNode = document.createTextNode("");
input.appendChild(textNode);
}
range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
range.collapse(true);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
//input.focus();
} else if (input.createTextRange) {
range = input.createTextRange();
range.collapse(true);
range.moveEnd("character", end);
range.moveStart("character", begin);
range.select();
}
}
}
} else {
if ("selectionStart" in input && "selectionEnd" in input) {
begin = input.selectionStart;
end = input.selectionEnd;
} else if (window.getSelection) {
range = window.getSelection().getRangeAt(0);
if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
begin = range.startOffset;
end = range.endOffset;
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
end = begin + range.text.length;
}
var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
input.inputmask.caretPos = {begin: begin, end: end}; //track caret internally
if (opts.insertModeVisual && opts.insertMode === false && begin === end) {
if (!isDelete) {
end++; //set visualization for insert/overwrite mode
}
}
if (input === (input.inputmask.shadowRoot || input.ownerDocument).activeElement) {
if ("setSelectionRange" in input) {
input.setSelectionRange(begin, end);
} else if (window.getSelection) {
range = document.createRange();
if (input.firstChild === undefined || input.firstChild === null) {
var textNode = document.createTextNode("");
input.appendChild(textNode);
}
range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
range.collapse(true);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
//input.focus();
} else if (input.createTextRange) {
range = input.createTextRange();
range.collapse(true);
range.moveEnd("character", end);
range.moveStart("character", begin);
range.select();
}
}
}
} else {
if ("selectionStart" in input && "selectionEnd" in input) {
begin = input.selectionStart;
end = input.selectionEnd;
} else if (window.getSelection) {
range = window.getSelection().getRangeAt(0);
if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
begin = range.startOffset;
end = range.endOffset;
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
end = begin + range.text.length;
}
// if (opts.insertModeVisual && opts.insertMode === false && begin === (end - 1)) end--; //correct caret for insert/overwrite mode
// if (opts.insertModeVisual && opts.insertMode === false && begin === (end - 1)) end--; //correct caret for insert/overwrite mode
/*eslint-disable consistent-return */
return {
"begin": notranslate ? begin : translatePosition.call(inputmask, begin),
"end": notranslate ? end : translatePosition.call(inputmask, end)
};
/*eslint-enable consistent-return */
}
/*eslint-disable consistent-return */
return {
"begin": notranslate ? begin : translatePosition.call(inputmask, begin),
"end": notranslate ? end : translatePosition.call(inputmask, end)
};
/*eslint-enable consistent-return */
}
}

@@ -112,43 +112,43 @@

function determineLastRequiredPosition(returnDefinition) {
const inputmask = this,
maskset = this.maskset,
$ = this.dependencyLib;
const inputmask = this,
maskset = this.maskset,
$ = this.dependencyLib;
var buffer = getMaskTemplate.call(inputmask, true, getLastValidPosition.call(inputmask), true, true),
bl = buffer.length,
pos, lvp = getLastValidPosition.call(inputmask),
positions = {},
lvTest = maskset.validPositions[lvp],
ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
testPos;
for (pos = lvp + 1; pos < buffer.length; pos++) {
testPos = getTestTemplate.call(inputmask, pos, ndxIntlzr, pos - 1);
ndxIntlzr = testPos.locator.slice();
positions[pos] = $.extend(true, {}, testPos);
}
var buffer = getMaskTemplate.call(inputmask, true, getLastValidPosition.call(inputmask), true, true),
bl = buffer.length,
pos, lvp = getLastValidPosition.call(inputmask),
positions = {},
lvTest = maskset.validPositions[lvp],
ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
testPos;
for (pos = lvp + 1; pos < buffer.length; pos++) {
testPos = getTestTemplate.call(inputmask, pos, ndxIntlzr, pos - 1);
ndxIntlzr = testPos.locator.slice();
positions[pos] = $.extend(true, {}, testPos);
}
var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
for (pos = bl - 1; pos > lvp; pos--) {
testPos = positions[pos];
if ((testPos.match.optionality ||
(testPos.match.optionalQuantifier && testPos.match.newBlockMarker) ||
(lvTestAlt &&
(
(lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.static != true) ||
(testPos.match.static === true &&
testPos.locator[lvTest.alternation] &&
checkAlternationMatch.call(inputmask, testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) &&
getTests.call(inputmask, pos)[0].def !== "")
)
)) &&
buffer[pos] === getPlaceholder.call(inputmask, pos, testPos.match)) {
bl--;
} else {
break;
}
}
return returnDefinition ? {
"l": bl,
"def": positions[bl] ? positions[bl].match : undefined
} : bl;
var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
for (pos = bl - 1; pos > lvp; pos--) {
testPos = positions[pos];
if ((testPos.match.optionality ||
(testPos.match.optionalQuantifier && testPos.match.newBlockMarker) ||
(lvTestAlt &&
(
(lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.static != true) ||
(testPos.match.static === true &&
testPos.locator[lvTest.alternation] &&
checkAlternationMatch.call(inputmask, testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) &&
getTests.call(inputmask, pos)[0].def !== "")
)
)) &&
buffer[pos] === getPlaceholder.call(inputmask, pos, testPos.match)) {
bl--;
} else {
break;
}
}
return returnDefinition ? {
"l": bl,
"def": positions[bl] ? positions[bl].match : undefined
} : bl;
}

@@ -158,73 +158,73 @@

function determineNewCaretPosition(selectedCaret, tabbed, positionCaretOnClick) {
const inputmask = this,
maskset = this.maskset,
opts = this.opts;
const inputmask = this,
maskset = this.maskset,
opts = this.opts;
function doRadixFocus(clickPos) {
if (opts.radixPoint !== "" && opts.digits !== 0) {
var vps = maskset.validPositions;
if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder.call(inputmask, clickPos))) {
if (clickPos < seekNext.call(inputmask, -1)) return true;
var radixPos = getBuffer.call(inputmask).indexOf(opts.radixPoint);
if (radixPos !== -1) {
for (var vp in vps) {
if (vps[vp] && radixPos < vp && vps[vp].input !== getPlaceholder.call(inputmask, vp)) {
return false;
}
}
return true;
}
}
}
return false;
}
function doRadixFocus(clickPos) {
if (opts.radixPoint !== "" && opts.digits !== 0) {
var vps = maskset.validPositions;
if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder.call(inputmask, clickPos))) {
if (clickPos < seekNext.call(inputmask, -1)) return true;
var radixPos = getBuffer.call(inputmask).indexOf(opts.radixPoint);
if (radixPos !== -1) {
for (let vp = 0, vpl = vps.length; vp < vpl; vp++) {
if (vps[vp] && radixPos < vp && vps[vp].input !== getPlaceholder.call(inputmask, vp)) {
return false;
}
}
return true;
}
}
}
return false;
}
if (tabbed) {
if (inputmask.isRTL) {
selectedCaret.end = selectedCaret.begin;
} else {
selectedCaret.begin = selectedCaret.end;
}
}
if (selectedCaret.begin === selectedCaret.end) {
positionCaretOnClick = positionCaretOnClick || opts.positionCaretOnClick;
switch (positionCaretOnClick) {
case "none":
break;
case "select":
selectedCaret = {begin: 0, end: getBuffer.call(inputmask).length};
break;
case "ignore":
selectedCaret.end = selectedCaret.begin = seekNext.call(inputmask, getLastValidPosition.call(inputmask));
break;
case "radixFocus":
if (doRadixFocus(selectedCaret.begin)) {
var radixPos = getBuffer.call(inputmask).join("").indexOf(opts.radixPoint);
selectedCaret.end = selectedCaret.begin = opts.numericInput ? seekNext.call(inputmask, radixPos) : radixPos;
break;
} //fallback to lvp
// eslint-disable-next-line no-fallthrough
default: //lvp:
var clickPosition = selectedCaret.begin,
lvclickPosition = getLastValidPosition.call(inputmask, clickPosition, true),
lastPosition = seekNext.call(inputmask, (lvclickPosition === -1 && !isMask.call(inputmask, 0)) ? -1 : lvclickPosition);
if (tabbed) {
if (inputmask.isRTL) {
selectedCaret.end = selectedCaret.begin;
} else {
selectedCaret.begin = selectedCaret.end;
}
}
if (selectedCaret.begin === selectedCaret.end) {
positionCaretOnClick = positionCaretOnClick || opts.positionCaretOnClick;
switch (positionCaretOnClick) {
case "none":
break;
case "select":
selectedCaret = {begin: 0, end: getBuffer.call(inputmask).length};
break;
case "ignore":
selectedCaret.end = selectedCaret.begin = seekNext.call(inputmask, getLastValidPosition.call(inputmask));
break;
case "radixFocus":
if (doRadixFocus(selectedCaret.begin)) {
var radixPos = getBuffer.call(inputmask).join("").indexOf(opts.radixPoint);
selectedCaret.end = selectedCaret.begin = opts.numericInput ? seekNext.call(inputmask, radixPos) : radixPos;
break;
} //fallback to lvp
// eslint-disable-next-line no-fallthrough
default: //lvp:
var clickPosition = selectedCaret.begin,
lvclickPosition = getLastValidPosition.call(inputmask, clickPosition, true),
lastPosition = seekNext.call(inputmask, (lvclickPosition === -1 && !isMask.call(inputmask, 0)) ? -1 : lvclickPosition);
if (clickPosition <= lastPosition) {
selectedCaret.end = selectedCaret.begin = !isMask.call(inputmask, clickPosition, false, true) ? seekNext.call(inputmask, clickPosition) : clickPosition;
} else {
var lvp = maskset.validPositions[lvclickPosition],
tt = getTestTemplate.call(inputmask, lastPosition, lvp ? lvp.match.locator : undefined, lvp),
placeholder = getPlaceholder.call(inputmask, lastPosition, tt.match);
if ((placeholder !== "" && getBuffer.call(inputmask)[lastPosition] !== placeholder && tt.match.optionalQuantifier !== true && tt.match.newBlockMarker !== true) || (!isMask.call(inputmask, lastPosition, opts.keepStatic, true) && tt.match.def === placeholder)) {
var newPos = seekNext.call(inputmask, lastPosition);
if (clickPosition >= newPos || clickPosition === lastPosition) {
lastPosition = newPos;
}
}
selectedCaret.end = selectedCaret.begin = lastPosition;
}
}
if (clickPosition <= lastPosition) {
selectedCaret.end = selectedCaret.begin = !isMask.call(inputmask, clickPosition, false, true) ? seekNext.call(inputmask, clickPosition) : clickPosition;
} else {
var lvp = maskset.validPositions[lvclickPosition],
tt = getTestTemplate.call(inputmask, lastPosition, lvp ? lvp.match.locator : undefined, lvp),
placeholder = getPlaceholder.call(inputmask, lastPosition, tt.match);
if ((placeholder !== "" && getBuffer.call(inputmask)[lastPosition] !== placeholder && tt.match.optionalQuantifier !== true && tt.match.newBlockMarker !== true) || (!isMask.call(inputmask, lastPosition, opts.keepStatic, true) && tt.match.def === placeholder)) {
var newPos = seekNext.call(inputmask, lastPosition);
if (clickPosition >= newPos || clickPosition === lastPosition) {
lastPosition = newPos;
}
}
selectedCaret.end = selectedCaret.begin = lastPosition;
}
}
return selectedCaret;
}
return selectedCaret;
}
}

@@ -235,9 +235,9 @@

function getBuffer(noCache) {
const inputmask = this, maskset = this.maskset;
const inputmask = this, maskset = this.maskset;
if (maskset.buffer === undefined || noCache === true) {
maskset.buffer = getMaskTemplate.call(inputmask, true, getLastValidPosition.call(inputmask), true);
if (maskset._buffer === undefined) maskset._buffer = maskset.buffer.slice();
}
return maskset.buffer;
if (maskset.buffer === undefined || noCache === true) {
maskset.buffer = getMaskTemplate.call(inputmask, true, getLastValidPosition.call(inputmask), true);
if (maskset._buffer === undefined) maskset._buffer = maskset.buffer.slice();
}
return maskset.buffer;
}

@@ -247,10 +247,10 @@

function getBufferTemplate() {
const inputmask = this, maskset = this.maskset;
const inputmask = this, maskset = this.maskset;
if (maskset._buffer === undefined) {
//generate template
maskset._buffer = getMaskTemplate.call(inputmask, false, 1);
if (maskset.buffer === undefined) maskset.buffer = maskset._buffer.slice();
}
return maskset._buffer;
if (maskset._buffer === undefined) {
//generate template
maskset._buffer = getMaskTemplate.call(inputmask, false, 1);
if (maskset.buffer === undefined) maskset.buffer = maskset._buffer.slice();
}
return maskset._buffer;
}

@@ -260,16 +260,15 @@

function getLastValidPosition(closestTo, strict, validPositions) {
const maskset = this.maskset;
const maskset = this.maskset;
var before = -1,
after = -1,
valids = validPositions || maskset.validPositions; //for use in valhook ~ context switch
if (closestTo === undefined) closestTo = -1;
for (var posNdx in valids) {
var psNdx = parseInt(posNdx);
if (valids[psNdx] && (strict || valids[psNdx].generatedInput !== true)) {
if (psNdx <= closestTo) before = psNdx;
if (psNdx >= closestTo) after = psNdx;
}
}
return (before === -1 || before == closestTo) ? after : after == -1 ? before : (closestTo - before) < (after - closestTo) ? before : after;
var before = -1,
after = -1,
valids = validPositions || maskset.validPositions; //for use in valhook ~ context switch
if (closestTo === undefined) closestTo = -1;
for (var psNdx = 0, vpl = valids.length; psNdx < vpl; psNdx++) {
if (valids[psNdx] && (strict || valids[psNdx].generatedInput !== true)) {
if (psNdx <= closestTo) before = psNdx;
if (psNdx >= closestTo) after = psNdx;
}
}
return (before === -1 || before == closestTo) ? after : after == -1 ? before : (closestTo - before) < (after - closestTo) ? before : after;
}

@@ -279,26 +278,26 @@

function isMask(pos, strict, fuzzy) {
const inputmask = this, maskset = this.maskset;
const inputmask = this, maskset = this.maskset;
var test = getTestTemplate.call(inputmask, pos).match;
if (test.def === "") test = getTest.call(inputmask, pos).match;
var test = getTestTemplate.call(inputmask, pos).match;
if (test.def === "") test = getTest.call(inputmask, pos).match;
if (test.static !== true) {
return test.fn;
}
if (fuzzy === true && (maskset.validPositions[pos] !== undefined && maskset.validPositions[pos].generatedInput !== true)) {
return true;
}
if (test.static !== true) {
return test.fn;
}
if (fuzzy === true && (maskset.validPositions[pos] !== undefined && maskset.validPositions[pos].generatedInput !== true)) {
return true;
}
if (strict !== true && pos > -1) {
if (fuzzy) { //check on the number of tests
var tests = getTests.call(inputmask, pos);
return tests.length > (1 + (tests[tests.length - 1].match.def === "" ? 1 : 0));
}
//else based on the template
var testTemplate = determineTestTemplate.call(inputmask, pos, getTests.call(inputmask, pos));
var testPlaceHolder = getPlaceholder.call(inputmask, pos, testTemplate.match);
return testTemplate.match.def !== testPlaceHolder;
if (strict !== true && pos > -1) {
if (fuzzy) { //check on the number of tests
var tests = getTests.call(inputmask, pos);
return tests.length > (1 + (tests[tests.length - 1].match.def === "" ? 1 : 0));
}
//else based on the template
var testTemplate = determineTestTemplate.call(inputmask, pos, getTests.call(inputmask, pos));
var testPlaceHolder = getPlaceholder.call(inputmask, pos, testTemplate.match);
return testTemplate.match.def !== testPlaceHolder;
}
return false;
}
return false;
}

@@ -308,9 +307,9 @@

function resetMaskSet(soft) {
const maskset = this.maskset;
const maskset = this.maskset;
maskset.buffer = undefined;
if (soft !== true) {
maskset.validPositions = {};
maskset.p = 0;
}
maskset.buffer = undefined;
if (soft !== true) {
maskset.validPositions = [];
maskset.p = 0;
}
}

@@ -320,12 +319,12 @@

function seekNext(pos, newBlock, fuzzy) {
const inputmask = this;
const inputmask = this;
if (fuzzy === undefined) fuzzy = true;
var position = pos + 1;
while (getTest.call(inputmask, position).match.def !== "" &&
((newBlock === true && (getTest.call(inputmask, position).match.newBlockMarker !== true || !isMask.call(inputmask, position, undefined, true))) ||
(newBlock !== true && !isMask.call(inputmask, position, undefined, fuzzy)))) {
position++;
}
return position;
if (fuzzy === undefined) fuzzy = true;
var position = pos + 1;
while (getTest.call(inputmask, position).match.def !== "" &&
((newBlock === true && (getTest.call(inputmask, position).match.newBlockMarker !== true || !isMask.call(inputmask, position, undefined, true))) ||
(newBlock !== true && !isMask.call(inputmask, position, undefined, fuzzy)))) {
position++;
}
return position;
}

@@ -335,13 +334,13 @@

function seekPrevious(pos, newBlock) {
const inputmask = this;
const inputmask = this;
var position = pos - 1;
if (pos <= 0) return 0;
var position = pos - 1;
if (pos <= 0) return 0;
while (position > 0 &&
((newBlock === true && (getTest.call(inputmask, position).match.newBlockMarker !== true || !isMask.call(inputmask, position, undefined, true))) ||
(newBlock !== true && !isMask.call(inputmask, position, undefined, true)))) {
position--;
}
return position;
while (position > 0 &&
((newBlock === true && (getTest.call(inputmask, position).match.newBlockMarker !== true || !isMask.call(inputmask, position, undefined, true))) ||
(newBlock !== true && !isMask.call(inputmask, position, undefined, true)))) {
position--;
}
return position;
}

@@ -351,11 +350,11 @@

function translatePosition(pos) {
const inputmask = this,
opts = this.opts,
el = this.el;
const inputmask = this,
opts = this.opts,
el = this.el;
if (inputmask.isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "") && el) {
pos = inputmask._valueGet().length - pos;
if (pos < 0) pos = 0;
}
return pos;
if (inputmask.isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "") && el) {
pos = inputmask._valueGet().length - pos;
if (pos < 0) pos = 0;
}
return pos;
}

@@ -98,3 +98,3 @@ export {

if (jitRenderStatic || jitMasking === false || jitMasking === undefined /*|| pos < lvp*/ || (typeof jitMasking === "number" && isFinite(jitMasking) && jitMasking > pos)) {
maskTemplate.push(includeMode === false ? test.nativeDef : getPlaceholder.call(inputmask, pos, test));
maskTemplate.push(includeMode === false ? test.nativeDef : getPlaceholder.call(inputmask, maskTemplate.length, test));
} else {

@@ -101,0 +101,0 @@ jitRenderStatic = false;

@@ -30,3 +30,3 @@ import {

var validPsClone = $.extend(true, {}, maskset.validPositions),
var validPsClone = $.extend(true, [], maskset.validPositions),
tstClone = $.extend(true, {}, maskset.tests),

@@ -114,3 +114,3 @@ lastAlt,

//reset & revert
maskset.validPositions = $.extend(true, {}, validPsClone);
maskset.validPositions = $.extend(true, [], validPsClone);
maskset.tests = $.extend(true, {}, tstClone); //refresh tests after possible alternating

@@ -298,3 +298,3 @@ if (maskset.excludes[decisionPos]) {

commandObj.remove.sort(function (a, b) {
return b.pos - a.pos;
return inputmask.isRTL ? a.pos - b.pos : b.pos - a.pos;
}).forEach(function (lmnt) {

@@ -308,3 +308,3 @@ revalidateMask.call(inputmask, { begin: lmnt, end: lmnt + 1 });

commandObj.insert.sort(function (a, b) {
return a.pos - b.pos;
return inputmask.isRTL ? b.pos - a.pos : a.pos - b.pos;
}).forEach(function (lmnt) {

@@ -458,3 +458,3 @@ if (lmnt.c !== "") {

resetMaskSet.call(inputmask, true);
maskset.validPositions = $.extend(true, {}, positionsClone); //revert validation changes
maskset.validPositions = $.extend(true, [], positionsClone); //revert validation changes
} else {

@@ -470,3 +470,3 @@ trackbackPositions.call(inputmask, undefined, maskPos, true);

resetMaskSet.call(inputmask, true);
maskset.validPositions = $.extend(true, {}, positionsClone); //revert validation changes
maskset.validPositions = $.extend(true, [], positionsClone); //revert validation changes
endResult = false;

@@ -660,3 +660,3 @@ }

if (!valid) {
maskset.validPositions = $.extend(true, {}, positionsClone);
maskset.validPositions = $.extend(true, [], positionsClone);
resetMaskSet.call(inputmask, true);

@@ -663,0 +663,0 @@ return false;

{
"name": "inputmask",
"version": "5.0.8-beta.17",
"version": "5.0.8-beta.25",
"description": "Inputmask is a javascript library which creates an input mask. Inputmask can run against vanilla javascript, jQuery and jqlite.",

@@ -5,0 +5,0 @@ "main": "dist/inputmask.js",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc