inputmask
Advanced tools
Comparing version 5.0.9-beta.39 to 5.0.9-beta.45
@@ -9,2 +9,5 @@ # Change Log | ||
### Updates | ||
- better handle unmatching alternations - #2277 | ||
- datetime alias | ||
- add support for mmm & mmmm #2751 (WIP) | ||
- Update IP extension to support greedy option. #2749 | ||
@@ -15,2 +18,3 @@ - Properly handle insertMode false in alternation logic. | ||
### Fixed | ||
- d/mm/yyyy is converted to d/m//yyyd #2394 (WIP) | ||
- how to get value from input-mask element? #2702 | ||
@@ -17,0 +21,0 @@ - Problem with seconds in format 'HH:MM:ss' #2745 |
/* | ||
Input Mask plugin extensions | ||
http://github.com/RobinHerbots/jquery.inputmask | ||
http://github.com/RobinHerbots/inputmask | ||
Copyright (c) Robin Herbots | ||
@@ -12,2 +12,3 @@ Licensed under the MIT license | ||
import {getMaskTemplate} from "../validation-tests"; | ||
import "./inputmask.date.i18n"; | ||
@@ -17,328 +18,343 @@ const $ = Inputmask.dependencyLib; | ||
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, | ||
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); | ||
} | ||
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" || fcode === "mmm" || fcode === "mmmm") ? 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)) || targetProp === "ampm" || fcode === "mmm" || fcode === "mmmm") | ||
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, #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 | ||
}; | ||
i18n = Inputmask.prototype.i18n, | ||
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: [i18n.monthNames.slice(0, 12).join("|"), function (val) { | ||
let mval = i18n.monthNames.slice(0, 12).findIndex(item => val.toLowerCase() === item.toLowerCase()); | ||
return Date.prototype.setMonth.call(this, mval); | ||
}, "month", function () { | ||
return pad(Date.prototype.getMonth.call(this) + 1, 2); | ||
}],//Month as a three-letter abbreviation. | ||
mmmm: [i18n.monthNames.slice(12, 24).join("|"), function (val) { | ||
let mval = i18n.monthNames.slice(12, 24).findIndex(item => val.toLowerCase() === item.toLowerCase()); | ||
return Date.prototype.setMonth.call(this, mval); | ||
}, "month", function () { | ||
return pad(Date.prototype.getMonth.call(this) + 1, 2); | ||
}], //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 && 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 && tokenMatch.targetMatch[0] === "yyyy" && currentResult.pos - tokenMatch.targetMatchIndex === 2) { | ||
currentResult.remove = currentResult.pos + 1; | ||
return currentResult; | ||
} | ||
} else if (dateParts.date.getMonth() == 2 && 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"]) && */!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 = []; | ||
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) { | ||
if (i + match.index == 0 && current[i] < minVal[i]) { | ||
curVal[i] = current[i]; | ||
forceCurrentValue = true; | ||
} else { | ||
curVal[i] = minVal[i]; | ||
} | ||
// ADD +1 to whole | ||
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 (!isNaN(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; | ||
} | ||
@@ -349,37 +365,43 @@ | ||
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 | ||
let mask = "", match, fcode, ndx = 0, placeHolder = {}; | ||
getTokenizer(opts).lastIndex = 0; | ||
while ((match = getTokenizer(opts).exec(format))) { | ||
if (dateObjValue === undefined) { | ||
if ((fcode = formatcode(match))) { | ||
mask += "(" + fcode[0] + ")"; | ||
placeHolder[ndx] = match[0].charAt(0); | ||
} else { | ||
switch (match[0]) { | ||
case "[": | ||
mask += "("; | ||
break; | ||
case "]": | ||
mask += ")?"; | ||
break; | ||
default: | ||
mask += escapeRegex(match[0]); | ||
placeHolder[ndx] = match[0].charAt(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]; | ||
} | ||
} | ||
ndx++; | ||
} | ||
if (dateObjValue === undefined && opts.placeholder === "") { | ||
opts.placeholder = placeHolder; | ||
} | ||
return mask; | ||
} | ||
@@ -389,39 +411,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 | ||
}; | ||
} | ||
@@ -431,164 +453,152 @@ | ||
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 = 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: "", | ||
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]; | ||
maskset.validPositions.splice(pos + 1, 1); | ||
} | ||
} | ||
} | ||
//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]; | ||
maskset.validPositions.splice(pos + 1, 1); | ||
} | ||
} | ||
} | ||
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); | ||
} | ||
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.key === keys.ArrowRight) { | ||
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.key === keys.ArrowRight) { | ||
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, | ||
insertModeVisual: false, | ||
shiftPositions: false, | ||
keepStatic: false, | ||
inputmode: "numeric", | ||
prefillYear: true //Allows to disable prefill for datetime year. | ||
} | ||
return initialValue; | ||
}, | ||
insertMode: false, | ||
insertModeVisual: false, | ||
shiftPositions: false, | ||
keepStatic: false, | ||
inputmode: "numeric", | ||
prefillYear: true //Allows to disable prefill for datetime year. | ||
} | ||
}); |
/* | ||
Input Mask plugin extensions | ||
http://github.com/RobinHerbots/jquery.inputmask | ||
http://github.com/RobinHerbots/inputmask | ||
Copyright (c) Robin Herbots | ||
@@ -5,0 +5,0 @@ Licensed under the MIT license |
/* | ||
Input Mask plugin extensions | ||
http://github.com/RobinHerbots/jquery.inputmask | ||
http://github.com/RobinHerbots/inputmask | ||
Copyright (c) Robin Herbots | ||
@@ -158,3 +158,3 @@ Licensed under the MIT license | ||
if (opts.definitions[opts.groupSeparator] === undefined) { | ||
//update separatot definition | ||
//update separator definition | ||
opts.definitions[opts.groupSeparator] = {}; | ||
@@ -161,0 +161,0 @@ opts.definitions[opts.groupSeparator].validator = "[" + opts.groupSeparator + "]"; |
@@ -23,283 +23,284 @@ /* | ||
function Inputmask(alias, options, internal) { | ||
//allow instanciating without new | ||
if (!(this instanceof Inputmask)) { | ||
return new Inputmask(alias, options, internal); | ||
} | ||
//allow instanciating without new | ||
if (!(this instanceof Inputmask)) { | ||
return new Inputmask(alias, options, internal); | ||
} | ||
this.dependencyLib = $; | ||
this.el = undefined; | ||
this.events = {}; | ||
this.maskset = undefined; | ||
this.dependencyLib = $; | ||
this.el = undefined; | ||
this.events = {}; | ||
this.maskset = undefined; | ||
if (internal !== true) { | ||
//init options | ||
if (Object.prototype.toString.call(alias) === "[object Object]") { | ||
options = alias; | ||
} else { | ||
options = options || {}; | ||
if (alias) options.alias = alias; | ||
} | ||
this.opts = $.extend(true, {}, this.defaults, options); | ||
this.noMasksCache = options && options.definitions !== undefined; | ||
this.userOptions = options || {}; //user passed options | ||
resolveAlias(this.opts.alias, options, this.opts); | ||
} | ||
if (internal !== true) { | ||
//init options | ||
if (Object.prototype.toString.call(alias) === "[object Object]") { | ||
options = alias; | ||
} else { | ||
options = options || {}; | ||
if (alias) options.alias = alias; | ||
} | ||
this.opts = $.extend(true, {}, this.defaults, options); | ||
this.noMasksCache = options && options.definitions !== undefined; | ||
this.userOptions = options || {}; //user passed options | ||
resolveAlias(this.opts.alias, options, this.opts); | ||
} | ||
//maskscope properties | ||
this.refreshValue = false; //indicate a refresh from the inputvalue is needed (form.reset) | ||
this.undoValue = undefined; | ||
this.$el = undefined; | ||
this.skipInputEvent = false; //skip when triggered from within inputmask | ||
this.validationEvent = false; | ||
this.ignorable = false; | ||
this.maxLength; | ||
this.mouseEnter = false; | ||
this.clicked = 0; | ||
this.originalPlaceholder = undefined; //needed for FF | ||
this.isComposing = false, //keydowncode == 229 compositionevent fallback | ||
this.hasAlternator = false; | ||
//maskscope properties | ||
this.refreshValue = false; //indicate a refresh from the inputvalue is needed (form.reset) | ||
this.undoValue = undefined; | ||
this.$el = undefined; | ||
this.skipInputEvent = false; //skip when triggered from within inputmask | ||
this.validationEvent = false; | ||
this.ignorable = false; | ||
this.maxLength; | ||
this.mouseEnter = false; | ||
this.clicked = 0; | ||
this.originalPlaceholder = undefined; //needed for FF | ||
this.isComposing = false, //keydowncode == 229 compositionevent fallback | ||
this.hasAlternator = false; | ||
} | ||
Inputmask.prototype = { | ||
dataAttribute: "data-inputmask", //data attribute prefix used for attribute binding | ||
//options default | ||
defaults: 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: {}, | ||
i18n: {}, | ||
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 (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; | ||
} | ||
//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; | ||
} | ||
@@ -309,37 +310,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]); | ||
}); | ||
}; | ||
@@ -346,0 +347,0 @@ |
@@ -27,3 +27,3 @@ import window from "./global/window"; | ||
im.mask(this.input); | ||
im.shadowRoot = shadow; //make the shadowRoot available | ||
this.input.inputmask.shadowRoot = shadow; //make the shadowRoot available | ||
} | ||
@@ -30,0 +30,0 @@ |
@@ -9,488 +9,488 @@ import $ from "./dependencyLibs/inputmask.dependencyLib"; | ||
function generateMaskSet(opts, nocache) { | ||
var ms; | ||
var ms; | ||
function preProcessMask(mask, {repeat, groupmarker, quantifiermarker, keepStatic}) { | ||
if (repeat > 0 || repeat === "*" || repeat === "+") { | ||
var repeatStart = repeat === "*" ? 0 : (repeat === "+" ? 1 : repeat); | ||
if(repeatStart != repeat) { | ||
mask = groupmarker[0] + mask + groupmarker[1] + quantifiermarker[0] + repeatStart + "," + repeat + quantifiermarker[1]; | ||
} else { | ||
// repeat the mask n times | ||
var msk = mask; | ||
for (let i = 1; i < repeatStart; i++) { | ||
mask += msk; | ||
} | ||
} | ||
} | ||
if (keepStatic === true) { | ||
let optionalRegex = "(.)\\[([^\\]]*)\\]", // "(?<p1>.)\\[(?<p2>[^\\]]*)\\]", remove named capture group @2428 | ||
maskMatches = mask.match(new RegExp(optionalRegex, "g")); | ||
maskMatches && maskMatches.forEach((m, i) => { | ||
let [p1, p2] = m.split("["); p2 = p2.replace("]", ""); | ||
mask = mask.replace(new RegExp(`${escapeRegex(p1)}\\[${escapeRegex(p2)}\\]`), | ||
p1.charAt(0) === p2.charAt(0) ? | ||
`(${p1}|${p1}${p2})` : | ||
`${p1}[${p2}]`); | ||
// console.log(mask); | ||
}); | ||
} | ||
function preProcessMask(mask, {repeat, groupmarker, quantifiermarker, keepStatic}) { | ||
if (repeat > 0 || repeat === "*" || repeat === "+") { | ||
var repeatStart = repeat === "*" ? 0 : (repeat === "+" ? 1 : repeat); | ||
if (repeatStart != repeat) { | ||
mask = groupmarker[0] + mask + groupmarker[1] + quantifiermarker[0] + repeatStart + "," + repeat + quantifiermarker[1]; | ||
} else { | ||
// repeat the mask n times | ||
var msk = mask; | ||
for (let i = 1; i < repeatStart; i++) { | ||
mask += msk; | ||
} | ||
} | ||
} | ||
if (keepStatic === true) { | ||
let optionalRegex = "(.)\\[([^\\]]*)\\]", // "(?<p1>.)\\[(?<p2>[^\\]]*)\\]", remove named capture group @2428 | ||
maskMatches = mask.match(new RegExp(optionalRegex, "g")); | ||
maskMatches && maskMatches.forEach((m, i) => { | ||
let [p1, p2] = m.split("["); | ||
p2 = p2.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; | ||
} | ||
return mask; | ||
} | ||
function generateMask(mask, metadata, opts) { | ||
var regexMask = false; | ||
if (mask === null || mask === "") { | ||
regexMask = opts.regex !== null; | ||
if (regexMask) { | ||
mask = opts.regex; | ||
mask = mask.replace(/^(\^)(.*)(\$)$/, "$2"); | ||
} else { | ||
regexMask = true; | ||
mask = ".*"; | ||
} | ||
} | ||
if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) { | ||
opts.placeholder = ""; | ||
} //hide placeholder with single non-greedy mask | ||
mask = preProcessMask(mask, opts); | ||
function generateMask(mask, metadata, opts) { | ||
var regexMask = false; | ||
if (mask === null || mask === "") { | ||
regexMask = opts.regex !== null; | ||
if (regexMask) { | ||
mask = opts.regex; | ||
mask = mask.replace(/^(\^)(.*)(\$)$/, "$2"); | ||
} else { | ||
regexMask = true; | ||
mask = ".*"; | ||
} | ||
} | ||
if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) { | ||
opts.placeholder = ""; | ||
} //hide placeholder with single non-greedy mask | ||
mask = preProcessMask(mask, opts); | ||
// console.log(mask); | ||
var masksetDefinition, maskdefKey; | ||
maskdefKey = regexMask ? "regex_" + opts.regex : opts.numericInput ? mask.split("").reverse().join("") : mask; | ||
if (opts.keepStatic !== null) { //keepstatic modifies the output from the testdefinitions ~ so differentiate in the maskcache | ||
maskdefKey = "ks_" + opts.keepStatic + maskdefKey; | ||
} | ||
// console.log(mask); | ||
var masksetDefinition, maskdefKey; | ||
maskdefKey = regexMask ? "regex_" + opts.regex : opts.numericInput ? mask.split("").reverse().join("") : mask; | ||
if (opts.keepStatic !== null) { //keepstatic modifies the output from the testdefinitions ~ so differentiate in the maskcache | ||
maskdefKey = "ks_" + opts.keepStatic + maskdefKey; | ||
} | ||
if(typeof opts.placeholder === "object") { //placeholder object modifies the output from the testdefinitions ~ so differentiate in the maskcache | ||
maskdefKey = "ph_" + JSON.stringify(opts.placeholder) + maskdefKey; | ||
} | ||
if (Inputmask.prototype.masksCache[maskdefKey] === undefined || nocache === true) { | ||
masksetDefinition = { | ||
"mask": mask, | ||
"maskToken": Inputmask.prototype.analyseMask(mask, regexMask, opts), | ||
"validPositions": [], | ||
"_buffer": undefined, | ||
"buffer": undefined, | ||
"tests": {}, | ||
"excludes": {}, //excluded alternations | ||
"metadata": metadata, | ||
"maskLength": undefined, | ||
"jitOffset": {} | ||
}; | ||
if (nocache !== true) { | ||
Inputmask.prototype.masksCache[maskdefKey] = masksetDefinition; | ||
masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]); | ||
} | ||
} else { | ||
masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]); | ||
} | ||
if (Inputmask.prototype.masksCache[maskdefKey] === undefined || nocache === true) { | ||
masksetDefinition = { | ||
"mask": mask, | ||
"maskToken": Inputmask.prototype.analyseMask(mask, regexMask, opts), | ||
"validPositions": [], | ||
"_buffer": undefined, | ||
"buffer": undefined, | ||
"tests": {}, | ||
"excludes": {}, //excluded alternations | ||
"metadata": metadata, | ||
"maskLength": undefined, | ||
"jitOffset": {} | ||
}; | ||
if (nocache !== true) { | ||
Inputmask.prototype.masksCache[maskdefKey] = masksetDefinition; | ||
masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]); | ||
} | ||
} else { | ||
masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]); | ||
} | ||
return masksetDefinition; | ||
} | ||
return masksetDefinition; | ||
} | ||
if (typeof opts.mask === "function") { //allow mask to be a preprocessing fn - should return a valid mask | ||
opts.mask = opts.mask(opts); | ||
} | ||
if (Array.isArray(opts.mask)) { | ||
if (opts.mask.length > 1) { | ||
if (opts.keepStatic === null) { //enable by default when passing multiple masks when the option is not explicitly specified | ||
opts.keepStatic = true; | ||
} | ||
var altMask = opts.groupmarker[0]; | ||
(opts.isRTL ? opts.mask.reverse() : opts.mask).forEach(function (msk) { | ||
if (altMask.length > 1) { | ||
altMask += opts.alternatormarker; | ||
} | ||
if (msk.mask !== undefined && typeof msk.mask !== "function") { | ||
altMask += msk.mask; | ||
} else { | ||
altMask += msk; | ||
} | ||
}); | ||
altMask += opts.groupmarker[1]; | ||
// console.log(altMask); | ||
return generateMask(altMask, opts.mask, opts); | ||
} else { | ||
opts.mask = opts.mask.pop(); | ||
} | ||
} | ||
if (opts.mask && opts.mask.mask !== undefined && typeof opts.mask.mask !== "function") { | ||
ms = generateMask(opts.mask.mask, opts.mask, opts); | ||
} else { | ||
ms = generateMask(opts.mask, opts.mask, opts); | ||
} | ||
if (opts.keepStatic === null) opts.keepStatic = false; | ||
return ms; | ||
if (typeof opts.mask === "function") { //allow mask to be a preprocessing fn - should return a valid mask | ||
opts.mask = opts.mask(opts); | ||
} | ||
if (Array.isArray(opts.mask)) { | ||
if (opts.mask.length > 1) { | ||
if (opts.keepStatic === null) { //enable by default when passing multiple masks when the option is not explicitly specified | ||
opts.keepStatic = true; | ||
} | ||
var altMask = opts.groupmarker[0]; | ||
(opts.isRTL ? opts.mask.reverse() : opts.mask).forEach(function (msk) { | ||
if (altMask.length > 1) { | ||
altMask += opts.alternatormarker; | ||
} | ||
if (msk.mask !== undefined && typeof msk.mask !== "function") { | ||
altMask += msk.mask; | ||
} else { | ||
altMask += msk; | ||
} | ||
}); | ||
altMask += opts.groupmarker[1]; | ||
// console.log(altMask); | ||
return generateMask(altMask, opts.mask, opts); | ||
} else { | ||
opts.mask = opts.mask.pop(); | ||
} | ||
} | ||
if (opts.mask && opts.mask.mask !== undefined && typeof opts.mask.mask !== "function") { | ||
ms = generateMask(opts.mask.mask, opts.mask, opts); | ||
} else { | ||
ms = generateMask(opts.mask, opts.mask, opts); | ||
} | ||
if (opts.keepStatic === null) opts.keepStatic = false; | ||
return ms; | ||
} | ||
function analyseMask(mask, regexMask, opts) { | ||
const tokenizer = /(?:[?*+]|\{[0-9+*]+(?:,[0-9+*]*)?(?:\|[0-9+*]*)?\})|[^.?*+^${[]()|\\]+|./g, | ||
//Thx to https://github.com/slevithan/regex-colorizer for the regexTokenizer regex | ||
regexTokenizer = /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g; | ||
var escaped = false, | ||
currentToken = new MaskToken(), | ||
match, | ||
m, | ||
openenings = [], | ||
maskTokens = [], | ||
openingToken, | ||
currentOpeningToken, | ||
alternator, | ||
lastMatch, | ||
closeRegexGroup = false; | ||
const tokenizer = /(?:[?*+]|\{[0-9+*]+(?:,[0-9+*]*)?(?:\|[0-9+*]*)?\})|[^.?*+^${[]()|\\]+|./g, | ||
//Thx to https://github.com/slevithan/regex-colorizer for the regexTokenizer regex | ||
regexTokenizer = /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g; | ||
var escaped = false, | ||
currentToken = new MaskToken(), | ||
match, | ||
m, | ||
openenings = [], | ||
maskTokens = [], | ||
openingToken, | ||
currentOpeningToken, | ||
alternator, | ||
lastMatch, | ||
closeRegexGroup = false; | ||
//test definition => {fn: RegExp/function, static: true/false optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition} | ||
function insertTestDefinition(mtoken, element, position) { | ||
position = position !== undefined ? position : mtoken.matches.length; | ||
var prevMatch = mtoken.matches[position - 1]; | ||
if (regexMask) { | ||
if (element.indexOf("[") === 0 || (escaped && /\\d|\\s|\\w|\\p/i.test(element)) || element === ".") { | ||
let flag = opts.casing ? "i" : ""; | ||
if (/\\p\{.*}/i.test(element)) | ||
flag += "u"; | ||
mtoken.matches.splice(position++, 0, { | ||
fn: new RegExp(element, flag), | ||
static: false, | ||
optionality: false, | ||
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element, | ||
casing: null, | ||
def: element, | ||
placeholder: undefined, | ||
nativeDef: element | ||
}); | ||
} else { | ||
if (escaped) element = element[element.length - 1]; | ||
element.split("").forEach(function (lmnt, ndx) { | ||
prevMatch = mtoken.matches[position - 1]; | ||
mtoken.matches.splice(position++, 0, { | ||
fn: /[a-z]/i.test((opts.staticDefinitionSymbol || lmnt)) ? new RegExp("[" + (opts.staticDefinitionSymbol || lmnt) + "]", opts.casing ? "i" : "") : null, | ||
static: true, | ||
optionality: false, | ||
newBlockMarker: prevMatch === undefined ? "master" : (prevMatch.def !== lmnt && prevMatch.static !== true), | ||
casing: null, | ||
def: opts.staticDefinitionSymbol || lmnt, | ||
placeholder: opts.staticDefinitionSymbol !== undefined ? lmnt : undefined, | ||
nativeDef: (escaped ? "'" : "") + lmnt | ||
}); | ||
}); | ||
} | ||
escaped = false; | ||
} else { | ||
var maskdef = (opts.definitions && opts.definitions[element]) || (opts.usePrototypeDefinitions && Inputmask.prototype.definitions[element]); | ||
if (maskdef && !escaped) { | ||
mtoken.matches.splice(position++, 0, { | ||
fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator, opts.casing ? "i" : "") : new function () { | ||
this.test = maskdef.validator; | ||
} : new RegExp("."), | ||
static: maskdef.static || false, | ||
optionality: maskdef.optional || false, | ||
defOptionality: maskdef.optional || false, //indicator for an optional from the definition | ||
newBlockMarker: (prevMatch === undefined || maskdef.optional) ? "master" : prevMatch.def !== (maskdef.definitionSymbol || element), | ||
casing: maskdef.casing, | ||
def: maskdef.definitionSymbol || element, | ||
placeholder: maskdef.placeholder, | ||
nativeDef: element, | ||
generated: maskdef.generated | ||
}); | ||
} else { | ||
mtoken.matches.splice(position++, 0, { | ||
fn: /[a-z]/i.test((opts.staticDefinitionSymbol || element)) ? new RegExp("[" + (opts.staticDefinitionSymbol || element) + "]", opts.casing ? "i" : "") : null, | ||
static: true, | ||
optionality: false, | ||
newBlockMarker: prevMatch === undefined ? "master" : (prevMatch.def !== element && prevMatch.static !== true), | ||
casing: null, | ||
def: opts.staticDefinitionSymbol || element, | ||
placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined, | ||
nativeDef: (escaped ? "'" : "") + element | ||
}); | ||
escaped = false; | ||
} | ||
} | ||
} | ||
//test definition => {fn: RegExp/function, static: true/false optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition} | ||
function insertTestDefinition(mtoken, element, position) { | ||
position = position !== undefined ? position : mtoken.matches.length; | ||
// console.log(element, position, currentToken.matches.length); | ||
var prevMatch = mtoken.matches[position - 1]; | ||
if (regexMask) { | ||
if (element.indexOf("[") === 0 || (escaped && /\\d|\\s|\\w|\\p/i.test(element)) || element === ".") { | ||
let flag = opts.casing ? "i" : ""; | ||
if (/\\p\{.*}/i.test(element)) | ||
flag += "u"; | ||
mtoken.matches.splice(position++, 0, { | ||
fn: new RegExp(element, flag), | ||
static: false, | ||
optionality: false, | ||
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element, | ||
casing: null, | ||
def: element, | ||
placeholder: typeof opts.placeholder === "object" ? opts.placeholder[currentToken.matches.length] : undefined, | ||
nativeDef: element | ||
}); | ||
} else { | ||
if (escaped) element = element[element.length - 1]; | ||
element.split("").forEach(function (lmnt, ndx) { | ||
prevMatch = mtoken.matches[position - 1]; | ||
mtoken.matches.splice(position++, 0, { | ||
fn: /[a-z]/i.test((opts.staticDefinitionSymbol || lmnt)) ? new RegExp("[" + (opts.staticDefinitionSymbol || lmnt) + "]", opts.casing ? "i" : "") : null, | ||
static: true, | ||
optionality: false, | ||
newBlockMarker: prevMatch === undefined ? "master" : (prevMatch.def !== lmnt && prevMatch.static !== true), | ||
casing: null, | ||
def: opts.staticDefinitionSymbol || lmnt, | ||
placeholder: opts.staticDefinitionSymbol !== undefined ? lmnt : typeof opts.placeholder === "object" ? opts.placeholder[currentToken.matches.length] : undefined, | ||
nativeDef: (escaped ? "'" : "") + lmnt | ||
}); | ||
}); | ||
} | ||
escaped = false; | ||
} else { | ||
var maskdef = (opts.definitions && opts.definitions[element]) || (opts.usePrototypeDefinitions && Inputmask.prototype.definitions[element]); | ||
if (maskdef && !escaped) { | ||
mtoken.matches.splice(position++, 0, { | ||
fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator, opts.casing ? "i" : "") : new function () { | ||
this.test = maskdef.validator; | ||
} : new RegExp("."), | ||
static: maskdef.static || false, | ||
optionality: maskdef.optional || false, | ||
defOptionality: maskdef.optional || false, //indicator for an optional from the definition | ||
newBlockMarker: (prevMatch === undefined || maskdef.optional) ? "master" : prevMatch.def !== (maskdef.definitionSymbol || element), | ||
casing: maskdef.casing, | ||
def: maskdef.definitionSymbol || element, | ||
placeholder: maskdef.placeholder, | ||
nativeDef: element, | ||
generated: maskdef.generated | ||
}); | ||
} else { | ||
mtoken.matches.splice(position++, 0, { | ||
fn: /[a-z]/i.test((opts.staticDefinitionSymbol || element)) ? new RegExp("[" + (opts.staticDefinitionSymbol || element) + "]", opts.casing ? "i" : "") : null, | ||
static: true, | ||
optionality: false, | ||
newBlockMarker: prevMatch === undefined ? "master" : (prevMatch.def !== element && prevMatch.static !== true), | ||
casing: null, | ||
def: opts.staticDefinitionSymbol || element, | ||
placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined, | ||
nativeDef: (escaped ? "'" : "") + element | ||
}); | ||
escaped = false; | ||
} | ||
} | ||
} | ||
function verifyGroupMarker(maskToken) { | ||
if (maskToken && maskToken.matches) { | ||
maskToken.matches.forEach(function (token, ndx) { | ||
var nextToken = maskToken.matches[ndx + 1]; | ||
if ((nextToken === undefined || (nextToken.matches === undefined || nextToken.isQuantifier === false)) && token && token.isGroup) { //this is not a group but a normal mask => convert | ||
token.isGroup = false; | ||
if (!regexMask) { | ||
insertTestDefinition(token, opts.groupmarker[0], 0); | ||
if (token.openGroup !== true) { | ||
insertTestDefinition(token, opts.groupmarker[1]); | ||
} | ||
} | ||
} | ||
verifyGroupMarker(token); | ||
}); | ||
} | ||
} | ||
function verifyGroupMarker(maskToken) { | ||
if (maskToken && maskToken.matches) { | ||
maskToken.matches.forEach(function (token, ndx) { | ||
var nextToken = maskToken.matches[ndx + 1]; | ||
if ((nextToken === undefined || (nextToken.matches === undefined || nextToken.isQuantifier === false)) && token && token.isGroup) { //this is not a group but a normal mask => convert | ||
token.isGroup = false; | ||
if (!regexMask) { | ||
insertTestDefinition(token, opts.groupmarker[0], 0); | ||
if (token.openGroup !== true) { | ||
insertTestDefinition(token, opts.groupmarker[1]); | ||
} | ||
} | ||
} | ||
verifyGroupMarker(token); | ||
}); | ||
} | ||
} | ||
function defaultCase() { | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
insertTestDefinition(currentOpeningToken, m); | ||
if (currentOpeningToken.isAlternator) { //handle alternator a | b case | ||
alternator = openenings.pop(); | ||
for (var mndx = 0; mndx < alternator.matches.length; mndx++) { | ||
if (alternator.matches[mndx].isGroup) alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group | ||
} | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
currentOpeningToken.matches.push(alternator); | ||
} else { | ||
currentToken.matches.push(alternator); | ||
} | ||
} | ||
} else { | ||
insertTestDefinition(currentToken, m); | ||
} | ||
} | ||
function defaultCase() { | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
insertTestDefinition(currentOpeningToken, m); | ||
if (currentOpeningToken.isAlternator) { //handle alternator a | b case | ||
alternator = openenings.pop(); | ||
for (var mndx = 0; mndx < alternator.matches.length; mndx++) { | ||
if (alternator.matches[mndx].isGroup) alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group | ||
} | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
currentOpeningToken.matches.push(alternator); | ||
} else { | ||
currentToken.matches.push(alternator); | ||
} | ||
} | ||
} else { | ||
insertTestDefinition(currentToken, m); | ||
} | ||
} | ||
function reverseTokens(maskToken) { | ||
function reverseStatic(st) { | ||
if (st === opts.optionalmarker[0]) { | ||
st = opts.optionalmarker[1]; | ||
} else if (st === opts.optionalmarker[1]) { | ||
st = opts.optionalmarker[0]; | ||
} else if (st === opts.groupmarker[0]) { | ||
st = opts.groupmarker[1]; | ||
} else if (st === opts.groupmarker[1]) st = opts.groupmarker[0]; | ||
function reverseTokens(maskToken) { | ||
function reverseStatic(st) { | ||
if (st === opts.optionalmarker[0]) { | ||
st = opts.optionalmarker[1]; | ||
} else if (st === opts.optionalmarker[1]) { | ||
st = opts.optionalmarker[0]; | ||
} else if (st === opts.groupmarker[0]) { | ||
st = opts.groupmarker[1]; | ||
} else if (st === opts.groupmarker[1]) st = opts.groupmarker[0]; | ||
return st; | ||
} | ||
return st; | ||
} | ||
maskToken.matches = maskToken.matches.reverse(); | ||
for (var match in maskToken.matches) { | ||
if (Object.prototype.hasOwnProperty.call(maskToken.matches, match)) { | ||
var intMatch = parseInt(match); | ||
if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier | ||
var qt = maskToken.matches[match]; | ||
maskToken.matches.splice(match, 1); | ||
maskToken.matches.splice(intMatch + 1, 0, qt); | ||
} | ||
if (maskToken.matches[match].matches !== undefined) { | ||
maskToken.matches[match] = reverseTokens(maskToken.matches[match]); | ||
} else { | ||
maskToken.matches[match] = reverseStatic(maskToken.matches[match]); | ||
} | ||
} | ||
} | ||
maskToken.matches = maskToken.matches.reverse(); | ||
for (var match in maskToken.matches) { | ||
if (Object.prototype.hasOwnProperty.call(maskToken.matches, match)) { | ||
var intMatch = parseInt(match); | ||
if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { //reposition quantifier | ||
var qt = maskToken.matches[match]; | ||
maskToken.matches.splice(match, 1); | ||
maskToken.matches.splice(intMatch + 1, 0, qt); | ||
} | ||
if (maskToken.matches[match].matches !== undefined) { | ||
maskToken.matches[match] = reverseTokens(maskToken.matches[match]); | ||
} else { | ||
maskToken.matches[match] = reverseStatic(maskToken.matches[match]); | ||
} | ||
} | ||
} | ||
return maskToken; | ||
} | ||
return maskToken; | ||
} | ||
function groupify(matches) { | ||
var groupToken = new MaskToken(true); | ||
groupToken.openGroup = false; | ||
groupToken.matches = matches; | ||
return groupToken; | ||
} | ||
function groupify(matches) { | ||
var groupToken = new MaskToken(true); | ||
groupToken.openGroup = false; | ||
groupToken.matches = matches; | ||
return groupToken; | ||
} | ||
function closeGroup() { | ||
// Group closing | ||
openingToken = openenings.pop(); | ||
openingToken.openGroup = false; //mark group as complete | ||
if (openingToken !== undefined) { | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
currentOpeningToken.matches.push(openingToken); | ||
if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case | ||
alternator = openenings.pop(); | ||
let altMatchesLength = alternator.matches[0].matches ? alternator.matches[0].matches.length : 1; | ||
for (var mndx = 0; mndx < alternator.matches.length; mndx++) { | ||
alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group | ||
alternator.matches[mndx].alternatorGroup = false; | ||
if (opts.keepStatic === null && altMatchesLength < (alternator.matches[mndx].matches ? alternator.matches[mndx].matches.length : 1)) { //enable by default when passing multiple masks when the option is not explicitly specified | ||
opts.keepStatic = true; | ||
} | ||
altMatchesLength = alternator.matches[mndx].matches ? alternator.matches[mndx].matches.length : 1; | ||
} | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
currentOpeningToken.matches.push(alternator); | ||
} else { | ||
currentToken.matches.push(alternator); | ||
} | ||
} | ||
} else { | ||
currentToken.matches.push(openingToken); | ||
} | ||
} else { | ||
defaultCase(); | ||
} | ||
} | ||
function closeGroup() { | ||
// Group closing | ||
openingToken = openenings.pop(); | ||
openingToken.openGroup = false; //mark group as complete | ||
if (openingToken !== undefined) { | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
currentOpeningToken.matches.push(openingToken); | ||
if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case | ||
alternator = openenings.pop(); | ||
for (var mndx = 0; mndx < alternator.matches.length; mndx++) { | ||
alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group | ||
alternator.matches[mndx].alternatorGroup = false; | ||
} | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
currentOpeningToken.matches.push(alternator); | ||
} else { | ||
currentToken.matches.push(alternator); | ||
} | ||
} | ||
} else { | ||
currentToken.matches.push(openingToken); | ||
} | ||
} else { | ||
defaultCase(); | ||
} | ||
} | ||
function groupQuantifier(matches) { | ||
var lastMatch = matches.pop(); | ||
if (lastMatch.isQuantifier) { | ||
lastMatch = groupify([matches.pop(), lastMatch]); | ||
} | ||
return lastMatch; | ||
} | ||
function groupQuantifier(matches) { | ||
var lastMatch = matches.pop(); | ||
if (lastMatch.isQuantifier) { | ||
lastMatch = groupify([matches.pop(), lastMatch]); | ||
} | ||
return lastMatch; | ||
} | ||
if (regexMask) { | ||
opts.optionalmarker[0] = undefined; | ||
opts.optionalmarker[1] = undefined; | ||
} | ||
// console.log(mask); | ||
while ((match = regexMask ? regexTokenizer.exec(mask) : tokenizer.exec(mask))) { | ||
// console.log(match); | ||
m = match[0]; | ||
if (regexMask) { | ||
opts.optionalmarker[0] = undefined; | ||
opts.optionalmarker[1] = undefined; | ||
} | ||
// console.log(mask); | ||
while ((match = regexMask ? regexTokenizer.exec(mask) : tokenizer.exec(mask))) { | ||
// console.log(match); | ||
m = match[0]; | ||
if (regexMask) { | ||
switch (m.charAt(0)) { | ||
//Quantifier | ||
case "?": | ||
m = "{0,1}"; | ||
break; | ||
case "+": | ||
case "*": | ||
m = "{" + m + "}"; | ||
break; | ||
case "|": | ||
//regex mask alternator ex: [01][0-9]|2[0-3] => ([01][0-9]|2[0-3]) | ||
if (openenings.length === 0) { //wrap the mask in a group to form a regex alternator ([01][0-9]|2[0-3]) | ||
var altRegexGroup = groupify(currentToken.matches); | ||
altRegexGroup.openGroup = true; | ||
openenings.push(altRegexGroup); | ||
currentToken.matches = []; | ||
closeRegexGroup = true; | ||
} | ||
break; | ||
} | ||
switch (m) { | ||
case "\\d": | ||
m = "[0-9]"; | ||
break; | ||
case "\\p": //Unicode Categories | ||
m += regexTokenizer.exec(mask)[0]; // { | ||
m += regexTokenizer.exec(mask)[0]; // ?} | ||
break; | ||
case "(?:": //non capturing group | ||
case "(?=": //lookahead | ||
case "(?!": //negative lookahead | ||
case "(?<=": //lookbehind | ||
case "(?<!": //negative lookbehind | ||
// treat as group | ||
break; | ||
} | ||
} | ||
if (regexMask) { | ||
switch (m.charAt(0)) { | ||
//Quantifier | ||
case "?": | ||
m = "{0,1}"; | ||
break; | ||
case "+": | ||
case "*": | ||
m = "{" + m + "}"; | ||
break; | ||
case "|": | ||
//regex mask alternator ex: [01][0-9]|2[0-3] => ([01][0-9]|2[0-3]) | ||
if (openenings.length === 0) { //wrap the mask in a group to form a regex alternator ([01][0-9]|2[0-3]) | ||
var altRegexGroup = groupify(currentToken.matches); | ||
altRegexGroup.openGroup = true; | ||
openenings.push(altRegexGroup); | ||
currentToken.matches = []; | ||
closeRegexGroup = true; | ||
} | ||
break; | ||
} | ||
switch (m) { | ||
case "\\d": | ||
m = "[0-9]"; | ||
break; | ||
case "\\p": //Unicode Categories | ||
m += regexTokenizer.exec(mask)[0]; // { | ||
m += regexTokenizer.exec(mask)[0]; // ?} | ||
break; | ||
case "(?:": //non capturing group | ||
case "(?=": //lookahead | ||
case "(?!": //negative lookahead | ||
case "(?<=": //lookbehind | ||
case "(?<!": //negative lookbehind | ||
// treat as group | ||
break; | ||
} | ||
} | ||
if (escaped) { | ||
defaultCase(); | ||
continue; | ||
} | ||
switch (m.charAt(0)) { | ||
case "$": | ||
case "^": | ||
//ignore beginswith and endswith as in masking this makes no point | ||
if (!regexMask) { | ||
defaultCase(); | ||
} | ||
break; | ||
case opts.escapeChar: | ||
escaped = true; | ||
if (regexMask) defaultCase(); | ||
break; | ||
// optional closing | ||
case opts.optionalmarker[1]: | ||
case opts.groupmarker[1]: | ||
closeGroup(); | ||
break; | ||
case opts.optionalmarker[0]: | ||
// optional opening | ||
openenings.push(new MaskToken(false, true)); | ||
break; | ||
case opts.groupmarker[0]: | ||
// Group opening | ||
openenings.push(new MaskToken(true)); | ||
break; | ||
case opts.quantifiermarker[0]: | ||
//Quantifier | ||
var quantifier = new MaskToken(false, false, true); | ||
if (escaped) { | ||
defaultCase(); | ||
continue; | ||
} | ||
switch (m.charAt(0)) { | ||
case "$": | ||
case "^": | ||
//ignore beginswith and endswith as in masking this makes no point | ||
if (!regexMask) { | ||
defaultCase(); | ||
} | ||
break; | ||
case opts.escapeChar: | ||
escaped = true; | ||
if (regexMask) defaultCase(); | ||
break; | ||
// optional closing | ||
case opts.optionalmarker[1]: | ||
case opts.groupmarker[1]: | ||
closeGroup(); | ||
break; | ||
case opts.optionalmarker[0]: | ||
// optional opening | ||
openenings.push(new MaskToken(false, true)); | ||
break; | ||
case opts.groupmarker[0]: | ||
// Group opening | ||
openenings.push(new MaskToken(true)); | ||
break; | ||
case opts.quantifiermarker[0]: | ||
//Quantifier | ||
var quantifier = new MaskToken(false, false, true); | ||
m = m.replace(/[{}?]/g, ""); //? matches lazy quantifiers | ||
var mqj = m.split("|"), | ||
mq = mqj[0].split(","), | ||
mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), | ||
mq1 = mq.length === 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1])), | ||
mqJit = isNaN(mqj[1]) ? mqj[1] : parseInt(mqj[1]); | ||
if (mq0 === "*" || mq0 === "+") { | ||
mq0 = mq1 === "*" ? 0 : 1; | ||
} | ||
quantifier.quantifier = { | ||
min: mq0, | ||
max: mq1, | ||
jit: mqJit | ||
}; | ||
var matches = openenings.length > 0 ? openenings[openenings.length - 1].matches : currentToken.matches; | ||
match = matches.pop(); | ||
// if (match.isAlternator) { //handle quantifier in an alternation [0-9]{2}|[0-9]{3} | ||
// matches.push(match); //push back alternator | ||
// matches = match.matches; //remap target matches | ||
// var groupToken = new MaskToken(true); | ||
// var tmpMatch = matches.pop(); | ||
// matches.push(groupToken); //push the group | ||
// matches = groupToken.matches; | ||
// match = tmpMatch; | ||
// } | ||
if (!match.isGroup) { | ||
match = groupify([match]); | ||
} | ||
matches.push(match); | ||
matches.push(quantifier); | ||
m = m.replace(/[{}?]/g, ""); //? matches lazy quantifiers | ||
var mqj = m.split("|"), | ||
mq = mqj[0].split(","), | ||
mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), | ||
mq1 = mq.length === 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1])), | ||
mqJit = isNaN(mqj[1]) ? mqj[1] : parseInt(mqj[1]); | ||
if (mq0 === "*" || mq0 === "+") { | ||
mq0 = mq1 === "*" ? 0 : 1; | ||
} | ||
quantifier.quantifier = { | ||
min: mq0, | ||
max: mq1, | ||
jit: mqJit | ||
}; | ||
var matches = openenings.length > 0 ? openenings[openenings.length - 1].matches : currentToken.matches; | ||
match = matches.pop(); | ||
// if (match.isAlternator) { //handle quantifier in an alternation [0-9]{2}|[0-9]{3} | ||
// matches.push(match); //push back alternator | ||
// matches = match.matches; //remap target matches | ||
// var groupToken = new MaskToken(true); | ||
// var tmpMatch = matches.pop(); | ||
// matches.push(groupToken); //push the group | ||
// matches = groupToken.matches; | ||
// match = tmpMatch; | ||
// } | ||
if (!match.isGroup) { | ||
match = groupify([match]); | ||
} | ||
matches.push(match); | ||
matches.push(quantifier); | ||
break; | ||
case opts.alternatormarker: | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
var subToken = currentOpeningToken.matches[currentOpeningToken.matches.length - 1]; | ||
if (currentOpeningToken.openGroup && //regexp alt syntax | ||
(subToken.matches === undefined || (subToken.isGroup === false && subToken.isAlternator === false))) { //alternations within group | ||
lastMatch = openenings.pop(); | ||
} else { | ||
lastMatch = groupQuantifier(currentOpeningToken.matches); | ||
} | ||
} else { | ||
lastMatch = groupQuantifier(currentToken.matches); | ||
} | ||
if (lastMatch.isAlternator) { | ||
openenings.push(lastMatch); | ||
} else { | ||
if (lastMatch.alternatorGroup) { | ||
alternator = openenings.pop(); | ||
lastMatch.alternatorGroup = false; | ||
} else { | ||
alternator = new MaskToken(false, false, false, true); | ||
} | ||
alternator.matches.push(lastMatch); | ||
openenings.push(alternator); | ||
if (lastMatch.openGroup) { //regexp alt syntax | ||
lastMatch.openGroup = false; | ||
var alternatorGroup = new MaskToken(true); | ||
alternatorGroup.alternatorGroup = true; | ||
openenings.push(alternatorGroup); | ||
} | ||
} | ||
break; | ||
default: | ||
defaultCase(); | ||
} | ||
} | ||
break; | ||
case opts.alternatormarker: | ||
if (openenings.length > 0) { | ||
currentOpeningToken = openenings[openenings.length - 1]; | ||
var subToken = currentOpeningToken.matches[currentOpeningToken.matches.length - 1]; | ||
if (currentOpeningToken.openGroup && //regexp alt syntax | ||
(subToken.matches === undefined || (subToken.isGroup === false && subToken.isAlternator === false))) { //alternations within group | ||
lastMatch = openenings.pop(); | ||
} else { | ||
lastMatch = groupQuantifier(currentOpeningToken.matches); | ||
} | ||
} else { | ||
lastMatch = groupQuantifier(currentToken.matches); | ||
} | ||
if (lastMatch.isAlternator) { | ||
openenings.push(lastMatch); | ||
} else { | ||
if (lastMatch.alternatorGroup) { | ||
alternator = openenings.pop(); | ||
lastMatch.alternatorGroup = false; | ||
} else { | ||
alternator = new MaskToken(false, false, false, true); | ||
} | ||
alternator.matches.push(lastMatch); | ||
openenings.push(alternator); | ||
if (lastMatch.openGroup) { //regexp alt syntax | ||
lastMatch.openGroup = false; | ||
var alternatorGroup = new MaskToken(true); | ||
alternatorGroup.alternatorGroup = true; | ||
openenings.push(alternatorGroup); | ||
} | ||
} | ||
break; | ||
default: | ||
defaultCase(); | ||
} | ||
} | ||
if (closeRegexGroup) closeGroup(); | ||
if (closeRegexGroup) closeGroup(); | ||
while (openenings.length > 0) { | ||
openingToken = openenings.pop(); | ||
currentToken.matches.push(openingToken); | ||
} | ||
if (currentToken.matches.length > 0) { | ||
verifyGroupMarker(currentToken); | ||
maskTokens.push(currentToken); | ||
} | ||
while (openenings.length > 0) { | ||
openingToken = openenings.pop(); | ||
currentToken.matches.push(openingToken); | ||
} | ||
if (currentToken.matches.length > 0) { | ||
verifyGroupMarker(currentToken); | ||
maskTokens.push(currentToken); | ||
} | ||
if (opts.numericInput || opts.isRTL) { | ||
reverseTokens(maskTokens[0]); | ||
} | ||
// console.log(JSON.stringify(maskTokens)); | ||
return maskTokens; | ||
if (opts.numericInput || opts.isRTL) { | ||
reverseTokens(maskTokens[0]); | ||
} | ||
// console.log(JSON.stringify(maskTokens)); | ||
return maskTokens; | ||
} |
@@ -0,1 +1,3 @@ | ||
import {getLastValidPosition, seekNext} from "./positioning"; | ||
export { | ||
@@ -37,11 +39,18 @@ determineTestTemplate, | ||
test = test || getTest.call(inputmask, pos).match; | ||
if (test.placeholder !== undefined || returnPL === true) { | ||
return typeof test.placeholder === "function" ? test.placeholder(opts) : test.placeholder; | ||
if (test.placeholder !== "" && test.static === true && test.generated !== true) { //static and not dynamically generated ~ does not occur in regex mask ~ numeric alias def is not a valid entry | ||
const lvp = getLastValidPosition.call(inputmask, pos), | ||
nextPos = seekNext.call(inputmask, lvp); | ||
return (returnPL ? pos <= nextPos : pos < nextPos) ? (opts.staticDefinitionSymbol && test.static ? test.nativeDef : test.def) : typeof test.placeholder === "function" ? test.placeholder(opts) : test.placeholder; | ||
} else { | ||
return typeof test.placeholder === "function" ? test.placeholder(opts) : test.placeholder; | ||
} | ||
} else if (test.static === true) { | ||
if (pos > -1 && maskset.validPositions[pos] === undefined) { | ||
var tests = getTests.call(inputmask, pos), | ||
let tests = getTests.call(inputmask, pos), | ||
staticAlternations = [], | ||
prevTest; | ||
if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) { | ||
for (var i = 0; i < tests.length; i++) { | ||
if (typeof opts.placeholder === "string" && tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) { | ||
for (let i = 0; i < tests.length; i++) { | ||
if (tests[i].match.def !== "" && tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true && | ||
@@ -63,3 +72,3 @@ (tests[i].match.static === true || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, maskset, pos, true, opts) !== false))) { | ||
return opts.placeholder.charAt(pos % opts.placeholder.length); | ||
return typeof opts.placeholder === "object" ? test.def : opts.placeholder.charAt(pos % opts.placeholder.length); | ||
} | ||
@@ -211,4 +220,6 @@ | ||
if (source.match.def === target.match.nativeDef) return true; | ||
if ((opts.regex || (source.match.fn instanceof RegExp && target.match.fn instanceof RegExp)) && source.match.static !== true && target.match.static !== true) { //is regex a subset | ||
return expand(target.match.fn.toString().replace(/[[\]/]/g, "")).indexOf(expand(source.match.fn.toString().replace(/[[\]/]/g, ""))) !== -1; | ||
if (target.match.fn.source === ".") return true; | ||
return expand(target.match.fn.source.replace(/[[\]/]/g, "")).indexOf(expand(source.match.fn.source.replace(/[[\]/]/g, ""))) !== -1; | ||
} | ||
@@ -231,3 +242,4 @@ return false; | ||
latestMatch, | ||
cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : ""; | ||
cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : "", | ||
unMatchedAlternation = false; | ||
@@ -379,2 +391,15 @@ function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitializer contains a set of indexes to speedup searches in the mtokens | ||
function handleAlternator() { | ||
function isUnmatchedAlternation(alternateToken) { | ||
let matchesLength = alternateToken.matches[0].matches ? alternateToken.matches[0].matches.length : 1, | ||
matchesNewLength; | ||
for (let alndx = 0; alndx < alternateToken.matches.length; alndx++) { | ||
matchesNewLength = alternateToken.matches[alndx].matches ? alternateToken.matches[alndx].matches.length : 1; | ||
if (matchesLength !== matchesNewLength) { | ||
break; | ||
} | ||
} | ||
return matchesLength !== matchesNewLength; | ||
} | ||
inputmask.hasAlternator = true; | ||
@@ -385,4 +410,3 @@ var alternateToken = match, | ||
currentMatches = matches.slice(), | ||
loopNdxCnt = loopNdx.length, | ||
unMatchedAlternation = false; | ||
loopNdxCnt = loopNdx.length; | ||
var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1; | ||
@@ -427,3 +451,3 @@ if (altIndex === -1 || typeof altIndex === "string") { | ||
if (ndx === 0) { | ||
unMatchedAlternation = true; | ||
unMatchedAlternation = isUnmatchedAlternation(alternateToken); | ||
} | ||
@@ -443,3 +467,2 @@ if (tokenMatch && tokenMatch.matches && tokenMatch.matches.length > alternateToken.matches[0].matches.length) { | ||
dropMatch = false; | ||
altMatch.match.jit = altMatch.match.jit || unMatchedAlternation; //mark jit when there are unmatched alternations ex: mask: "(a|aa)" | ||
altMatch.alternation = altMatch.alternation || loopNdxCnt; | ||
@@ -472,2 +495,5 @@ setMergeLocators(altMatch); | ||
break; | ||
} else if (staticCanMatchDefinition(altMatch2, altMatch)) { | ||
setMergeLocators(altMatch2, altMatch); | ||
break; | ||
} | ||
@@ -484,4 +510,4 @@ } | ||
testPos = pos; | ||
insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate - needed for non-greedy option | ||
match = malternateMatches.length > 0; //set correct match state | ||
insertStop = matches.length > 0 && unMatchedAlternation; //insert a stopelemnt when there is an alternate - needed for non-greedy option | ||
match = malternateMatches.length > 0 && !unMatchedAlternation; //set correct match state | ||
@@ -654,3 +680,3 @@ //cloneback | ||
}, | ||
locator: [], | ||
locator: unMatchedAlternation ? [0] : [], //mark when there are unmatched alternations ex: mask: "(a|aa)" | ||
mloc: {}, | ||
@@ -664,2 +690,3 @@ cd: cacheDependency | ||
} else { | ||
// console.log("stored " + pos + " - " + JSON.stringify(matches)); | ||
maskset.tests[pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props | ||
@@ -666,0 +693,0 @@ result = maskset.tests[pos]; |
{ | ||
"name": "inputmask", | ||
"version": "5.0.9-beta.39", | ||
"version": "5.0.9-beta.45", | ||
"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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
978263
45
12747