1
0
Fork 0
mirror of https://github.com/DanielnetoDotCom/YouPHPTube synced 2025-10-05 02:39:46 +02:00

add inputmask

This commit is contained in:
DanieL 2022-09-21 13:51:50 -03:00
parent ab84f1e730
commit e07838c6c7
203 changed files with 29712 additions and 5216 deletions

View file

@ -0,0 +1,588 @@
/*
Input Mask plugin extensions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) Robin Herbots
Licensed under the MIT license
*/
import Inputmask from "../inputmask";
import keyCode from "../keycode.json";
import escapeRegex from "../escapeRegex";
import {seekNext} from "../positioning";
import {getMaskTemplate} from "../validation-tests";
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);
}
get date() {
if (this._date === undefined) {
this._date = new Date(1, 0, 1);
this.initDateObject(undefined, this.opts);
}
return this._date;
}
initDateObject(mask, opts) {
let match;
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(this.format))) {
let dynMatches = new RegExp("\\d+$").exec(match[0]),
fcode = dynMatches ? (match[0][0] + "x") : match[0],
value;
if (mask !== undefined) {
if (dynMatches) {
let lastIndex = getTokenizer(opts).lastIndex,
tokanMatch = getTokenMatch(match.index, opts);
getTokenizer(opts).lastIndex = lastIndex;
value = mask.slice(0, mask.indexOf(tokanMatch.nextMatch[0]));
} else {
value = mask.slice(0, fcode.length);
}
mask = mask.slice(value.length);
}
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);
}
}
reset() {
this._date = new Date(1, 0, 1);
}
reInit() {
this._date = undefined;
this.date;
}
}
let currentYear = new Date().getFullYear(),
useDateObject = false,
//supported codes for formatting
//http://blog.stevenlevithan.com/archives/date-time-format
//https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings?view=netframework-4.7
formatCode = { //regex, valueSetter, type, displayformatter
d: ["[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", Date.prototype.getDate], //Day of the month as digits; no leading zero for single-digit days.
dd: ["0[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", function () {
return pad(Date.prototype.getDate.call(this), 2);
}], //Day of the month as digits; leading zero for single-digit days.
ddd: [""], //Day of the week as a three-letter abbreviation.
dddd: [""], //Day of the week as its full name.
m: ["[1-9]|1[012]", function (val) {
let mval = val ? parseInt(val) : 0;
if (mval > 0) mval--;
return Date.prototype.setMonth.call(this, mval);
}, "month", function () {
return Date.prototype.getMonth.call(this) + 1;
}], //Month as digits; no leading zero for single-digit months.
mm: ["0[1-9]|1[012]", function (val) {
let mval = val ? parseInt(val) : 0;
if (mval > 0) mval--;
return Date.prototype.setMonth.call(this, mval);
}, "month", function () {
return pad(Date.prototype.getMonth.call(this) + 1, 2);
}], //Month as digits; leading zero for single-digit months.
mmm: [""], //Month as a three-letter abbreviation.
mmmm: [""], //Month as its full name.
yy: ["[0-9]{2}", Date.prototype.setFullYear, "year", function () {
return pad(Date.prototype.getFullYear.call(this), 2);
}], //Year as last two digits; leading zero for years less than 10.
yyyy: ["[0-9]{4}", Date.prototype.setFullYear, "year", function () {
return pad(Date.prototype.getFullYear.call(this), 4);
}],
h: ["[1-9]|1[0-2]", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no leading zero for single-digit hours (12-hour clock).
hh: ["0[1-9]|1[0-2]", Date.prototype.setHours, "hours", function () {
return pad(Date.prototype.getHours.call(this), 2);
}], //Hours; leading zero for single-digit hours (12-hour clock).
hx: [function (x) {
return `[0-9]{${x}}`;
}, Date.prototype.setHours, "hours", function (x) {
return Date.prototype.getHours;
}], //Hours; no limit; set maximum digits
H: ["1?[0-9]|2[0-3]", Date.prototype.setHours, "hours", Date.prototype.getHours], //Hours; no leading zero for single-digit hours (24-hour clock).
HH: ["0[0-9]|1[0-9]|2[0-3]", Date.prototype.setHours, "hours", function () {
return pad(Date.prototype.getHours.call(this), 2);
}], //Hours; leading zero for single-digit hours (24-hour clock).
Hx: [function (x) {
return `[0-9]{${x}}`;
}, Date.prototype.setHours, "hours", function (x) {
return function () {
return pad(Date.prototype.getHours.call(this), x);
};
}], //Hours; no limit; set maximum digits
M: ["[1-5]?[0-9]", Date.prototype.setMinutes, "minutes", Date.prototype.getMinutes], //Minutes; no leading zero for single-digit minutes. Uppercase M unlike CF timeFormat's m to avoid conflict with months.
MM: ["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setMinutes, "minutes", function () {
return pad(Date.prototype.getMinutes.call(this), 2);
}], //Minutes; leading zero for single-digit minutes. Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.
s: ["[1-5]?[0-9]", Date.prototype.setSeconds, "seconds", Date.prototype.getSeconds], //Seconds; no leading zero for single-digit seconds.
ss: ["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setSeconds, "seconds", function () {
return pad(Date.prototype.getSeconds.call(this), 2);
}], //Seconds; leading zero for single-digit seconds.
l: ["[0-9]{3}", Date.prototype.setMilliseconds, "milliseconds", function () {
return pad(Date.prototype.getMilliseconds.call(this), 3);
}], //Milliseconds. 3 digits.
L: ["[0-9]{2}", Date.prototype.setMilliseconds, "milliseconds", function () {
return pad(Date.prototype.getMilliseconds.call(this), 2);
}], //Milliseconds. 2 digits.
t: ["[ap]", setAMPM, "ampm", getAMPM, 1], //Lowercase, single-character time marker string: a or p.
tt: ["[ap]m", setAMPM, "ampm", getAMPM, 2], //two-character time marker string: am or pm.
T: ["[AP]", setAMPM, "ampm", getAMPM, 1], //single-character time marker string: A or P.
TT: ["[AP]M", setAMPM, "ampm", getAMPM, 2], //two-character time marker string: AM or PM.
Z: [".*", undefined, "Z", getTimeZoneAbbreviated], //US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500
o: [""], //GMT/UTC timezone offset, e.g. -0500 or +0230.
S: [""] //The date's ordinal suffix (st, nd, rd, or th).
},
formatAlias = {
isoDate: "yyyy-mm-dd", //2007-06-09
isoTime: "HH:MM:ss", //17:46:21
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", //2007-06-09T17:46:21
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" //2007-06-09T22:46:21Z
};
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);
}
}
function getAMPM() {
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;
}
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]);
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");
}
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]
}];
}
}
}
return currentResult;
}
function isValidDate(dateParts, currentResult, opts) {
if (!useDateObject) return true;
if (dateParts.rawday === undefined
|| (!isFinite(dateParts.rawday) && new Date(dateParts.date.getFullYear(), isFinite(dateParts.rawmonth) ? dateParts.month : dateParts.date.getMonth() + 1, 0).getDate() >= dateParts.day)
|| (dateParts.day == "29" && (!isFinite(dateParts.rawyear) || dateParts.rawyear === undefined || dateParts.rawyear === ""))
|| new Date(dateParts.date.getFullYear(), isFinite(dateParts.rawmonth) ? dateParts.month : dateParts.date.getMonth() + 1, 0).getDate() >= dateParts.day) {
return currentResult;
} else { //take corrective action if possible
if (dateParts.day == "29") {
var tokenMatch = getTokenMatch(currentResult.pos, opts);
if (tokenMatch.targetMatch[0] === "yyyy" && currentResult.pos - tokenMatch.targetMatchIndex === 2) {
currentResult.remove = currentResult.pos + 1;
return currentResult;
}
} else if (dateParts.month == "02" && dateParts.day == "30" && currentResult.c !== undefined) {
dateParts.day = "03";
dateParts.date.setDate(3);
dateParts.date.setMonth(1);
currentResult.insert = [{pos: currentResult.pos, c: "0"}, {pos: currentResult.pos + 1, c: currentResult.c}];
currentResult.caret = seekNext.call(this, currentResult.pos + 1);
return currentResult;
}
return false;
}
}
function isDateInRange(dateParts, result, opts, maskset, fromCheckval) {
if (!result) return result;
if (result && opts.min) {
if (/*useDateObject && (dateParts["year"] === undefined || dateParts["yearSet"]) && */opts.min.date.getTime() === opts.min.date.getTime()) {
let match;
dateParts.reset();
getTokenizer(opts).lastIndex = 0;
while ((match = getTokenizer(opts).exec(opts.inputFormat))) {
var fcode;
if ((fcode = formatcode(match))) {
if (fcode[3]) {
var setFn = fcode[1];
var current = dateParts[fcode[2]],
minVal = opts.min[fcode[2]],
maxVal = opts.max ? opts.max[fcode[2]] : minVal,
curVal = [];
let forceCurrentValue = false;
for (let i = 0; i < minVal.length; i++) {
if (maskset.validPositions[i + match.index] === undefined && !forceCurrentValue) {
curVal[i] = minVal[i];
// ADD +1 to whoile
if (fcode[2] === "year" && current.length - 1 == i && minVal != maxVal)
curVal = (parseInt(curVal.join("")) + 1).toString().split("");
if (fcode[2] === "ampm" && minVal != maxVal && opts.min.date.getTime() > dateParts.date.getTime())
curVal[i] = maxVal[i];
} else {
curVal[i] = current[i];
forceCurrentValue = forceCurrentValue || current[i] > minVal[i];
}
}
setFn.call(dateParts._date, curVal.join(""));
}
}
}
result = opts.min.date.getTime() <= dateParts.date.getTime();
dateParts.reInit();
}
}
if (result && opts.max) {
if (opts.max.date.getTime() === opts.max.date.getTime()) {
result = opts.max.date.getTime() >= dateParts.date.getTime();
}
}
return result;
}
//parse the given format and return a mask pattern
//when a dateObjValue is passed a datestring in the requested format is returned
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;
}
//padding function
function pad(val, len, right) {
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;
}
function importDate(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
};
}
Inputmask.extendAliases({
"datetime": {
mask: function (opts) {
//do not allow numeric input in datetime alias
opts.numericInput = false;
//localize
formatCode.S = opts.i18n.ordinalSuffix.join("|");
opts.inputFormat = formatAlias[opts.inputFormat] || opts.inputFormat; //resolve possible formatAlias
opts.displayFormat = formatAlias[opts.displayFormat] || opts.displayFormat || opts.inputFormat; //resolve possible formatAlias
opts.outputFormat = formatAlias[opts.outputFormat] || opts.outputFormat || opts.inputFormat; //resolve possible formatAlias
opts.placeholder = opts.placeholder !== "" ? opts.placeholder : opts.inputFormat.replace(/[[\]]/, "");
opts.regex = parse(opts.inputFormat, undefined, opts);
opts.min = analyseMask(opts.min, opts.inputFormat, opts);
opts.max = analyseMask(opts.max, opts.inputFormat, opts);
return null; //migrate to regex mask
},
placeholder: "", //set default as none (~ auto); when a custom placeholder is passed it will be used
inputFormat: "isoDateTime", //format used to input the date
displayFormat: null, //visual format when the input looses focus
outputFormat: null, //unmasking format
min: null, //needs to be in the same format as the inputfornat
max: null, //needs to be in the same format as the inputfornat,
skipOptionalPartCharacter: "",
// Internationalization strings
i18n: {
dayNames: [
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
],
ordinalSuffix: ["st", "nd", "rd", "th"]
},
preValidation: function (buffer, pos, c, isSelection, opts, maskset, caretPos, strict) {
if (strict) return true;
if (isNaN(c) && buffer[pos] !== c) {
var tokenMatch = getTokenMatch(pos, opts);
if (tokenMatch.nextMatch && tokenMatch.nextMatch[0] === c && tokenMatch.targetMatch[0].length > 1) {
var validator = formatCode[tokenMatch.targetMatch[0]][0];
if (new RegExp(validator).test("0" + buffer[pos - 1])) {
buffer[pos] = buffer[pos - 1];
buffer[pos - 1] = "0";
return {
fuzzy: true,
buffer: buffer,
refreshFromBuffer: {start: pos - 1, end: pos + 1},
pos: pos + 1
};
}
}
}
return true;
},
postValidation: function (buffer, pos, c, currentResult, opts, maskset, strict, fromCheckval) {
const inputmask = this;
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.fuzzy) {
buffer = currentResult.buffer;
pos = currentResult.pos;
}
//full validate target
tokenMatch = getTokenMatch(pos, opts);
if (tokenMatch.targetMatch && tokenMatch.targetMatch[0] && formatCode[tokenMatch.targetMatch[0]] !== undefined) {
let fcode = formatCode[tokenMatch.targetMatch[0]];
validator = fcode[0];
var part = buffer.slice(tokenMatch.targetMatchIndex, tokenMatch.targetMatchIndex + tokenMatch.targetMatch[0].length);
if (new RegExp(validator).test(part.join("")) === false && tokenMatch.targetMatch[0].length === 2 && maskset.validPositions[tokenMatch.targetMatchIndex] && maskset.validPositions[tokenMatch.targetMatchIndex + 1]) {
maskset.validPositions[tokenMatch.targetMatchIndex + 1].input = "0";
}
if (fcode[2] == "year") {
var _buffer = getMaskTemplate.call(inputmask, false, 1, undefined, true);
for (let i = pos + 1; i < buffer.length; i++) {
buffer[i] = _buffer[i];
delete maskset.validPositions[i];
}
}
}
var result = currentResult, dateParts = analyseMask(buffer.join(""), opts.inputFormat, opts);
if (result && dateParts.date.getTime() === dateParts.date.getTime()) { //check for a valid date ~ an invalid date returns NaN which isn't equal
if (opts.prefillYear) result = prefillYear(dateParts, result, opts);
result = isValidDate.call(inputmask, dateParts, result, opts);
result = isDateInRange(dateParts, result, opts, maskset, fromCheckval);
}
if (pos !== undefined && result && currentResult.pos !== pos) {
return {
buffer: parse(opts.inputFormat, dateParts, opts).split(""),
refreshFromBuffer: {start: pos, end: currentResult.pos},
pos: currentResult.caret || currentResult.pos //correct caret position
};
}
return result;
},
onKeyDown: function (e, buffer, caretPos, opts) {
var input = this;
if (e.ctrlKey && e.keyCode === keyCode.RIGHT) {
input.inputmask._valueSet(importDate(new Date(), opts));
$(input).trigger("setvalue");
}
},
onUnMask: function (maskedValue, unmaskedValue, opts) {
return unmaskedValue ? parse(opts.outputFormat, analyseMask(maskedValue, opts.inputFormat, opts), opts, true) : unmaskedValue;
},
casing: function (elem, test, pos, validPositions) {
if (test.nativeDef.indexOf("[ap]") == 0) return elem.toLowerCase();
if (test.nativeDef.indexOf("[AP]") == 0) return elem.toUpperCase();
return elem;
},
onBeforeMask: function (initialValue, opts) {
if (Object.prototype.toString.call(initialValue) === "[object Date]") {
initialValue = importDate(initialValue, opts);
}
return initialValue;
},
insertMode: false,
shiftPositions: false,
keepStatic: false,
inputmode: "numeric",
prefillYear: true //Allows to disable prefill for datetime year.
}
});

View file

@ -0,0 +1,133 @@
/*
Input Mask plugin extensions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) Robin Herbots
Licensed under the MIT license
*/
import Inputmask from "../inputmask";
import {getLastValidPosition} from "../positioning";
import {getMaskTemplate} from "../validation-tests";
//extra definitions
Inputmask.extendDefinitions({
"A": {
validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
casing: "upper" //auto uppercasing
},
"&": { //alfanumeric uppercasing
validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
casing: "upper"
},
"#": { //hexadecimal
validator: "[0-9A-Fa-f]",
casing: "upper"
}
});
var ipValidatorRegex = new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]");
function ipValidator(chrs, maskset, pos, strict, opts) {
if (pos - 1 > -1 && maskset.buffer[pos - 1] !== ".") {
chrs = maskset.buffer[pos - 1] + chrs;
if (pos - 2 > -1 && maskset.buffer[pos - 2] !== ".") {
chrs = maskset.buffer[pos - 2] + chrs;
} else chrs = "0" + chrs;
} else chrs = "00" + chrs;
return ipValidatorRegex.test(chrs);
}
Inputmask.extendAliases({
"cssunit": {
regex: "[+-]?[0-9]+\\.?([0-9]+)?(px|em|rem|ex|%|in|cm|mm|pt|pc)"
},
"url": { //needs update => https://en.wikipedia.org/wiki/URL
regex: "(https?|ftp)://.*",
autoUnmask: false,
keepStatic: false,
tabThrough: true
},
"ip": { //ip-address mask
mask: "i{1,3}.j{1,3}.k{1,3}.l{1,3}",
definitions: {
"i": {
validator: ipValidator
},
"j": {
validator: ipValidator
},
"k": {
validator: ipValidator
},
"l": {
validator: ipValidator
}
},
onUnMask: function (maskedValue, unmaskedValue, opts) {
return maskedValue;
},
inputmode: "decimal",
substitutes: {",": "."}
},
"email": {
//https://en.wikipedia.org/wiki/Domain_name#Domain_name_space
//https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
//should be extended with the toplevel domains at the end
mask: function (opts) {
var emailMask = "*{1,64}[.*{1,64}][.*{1,64}][.*{1,63}]@-{1,63}.-{1,63}[.-{1,63}][.-{1,63}]";
var mask = emailMask;
if (opts.separator) {
for (let i = 0; i < opts.quantifier; i++) {
mask += `[${opts.separator}${emailMask}]`;
}
}
return mask;
return opts.separator ? `${emailMask}(${opts.separator}${emailMask}){*}` : emailMask;
},
greedy: false,
casing: "lower",
separator: null,
quantifier: 5,
skipOptionalPartCharacter: "",
onBeforePaste: function (pastedValue, opts) {
pastedValue = pastedValue.toLowerCase();
return pastedValue.replace("mailto:", "");
},
definitions: {
"*": {
validator: "[0-9\uFF11-\uFF19A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5!#$%&'*+/=?^_`{|}~-]"
},
"-": {
validator: "[0-9A-Za-z-]"
}
},
onUnMask: function (maskedValue, unmaskedValue, opts) {
return maskedValue;
},
inputmode: "email"
},
"mac": {
mask: "##:##:##:##:##:##"
},
//https://en.wikipedia.org/wiki/Vehicle_identification_number
// see issue #1199
"vin": {
mask: "V{13}9{4}",
definitions: {
"V": {
validator: "[A-HJ-NPR-Za-hj-npr-z\\d]",
casing: "upper"
}
},
clearIncomplete: true,
autoUnmask: true
},
//http://rion.io/2013/09/10/validating-social-security-numbers-through-regular-expressions-2/
//https://en.wikipedia.org/wiki/Social_Security_number
"ssn": {
mask: "999-99-9999",
postValidation: function (buffer, pos, c, currentResult, opts, maskset, strict) {
var bffr = getMaskTemplate.call(this, true, getLastValidPosition.call(this), true, true);
return /^(?!219-09-9999|078-05-1120)(?!666|000|9.{2}).{3}-(?!00).{2}-(?!0{4}).{4}$/.test(bffr.join(""));
}
},
});

View file

@ -0,0 +1,631 @@
/*
Input Mask plugin extensions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) Robin Herbots
Licensed under the MIT license
*/
import Inputmask from "../inputmask";
import keyCode from "../keycode.json";
import escapeRegex from "../escapeRegex";
import {seekNext} from "../positioning";
const $ = Inputmask.dependencyLib;
function autoEscape(txt, opts) {
var escapedTxt = "";
for (var i = 0; i < txt.length; i++) {
if (Inputmask.prototype.definitions[txt.charAt(i)] ||
opts.definitions[txt.charAt(i)] ||
opts.optionalmarker[0] === txt.charAt(i) ||
opts.optionalmarker[1] === txt.charAt(i) ||
opts.quantifiermarker[0] === txt.charAt(i) ||
opts.quantifiermarker[1] === txt.charAt(i) ||
opts.groupmarker[0] === txt.charAt(i) ||
opts.groupmarker[1] === txt.charAt(i) ||
opts.alternatormarker === txt.charAt(i)) {
escapedTxt += "\\" + txt.charAt(i);
} else {
escapedTxt += txt.charAt(i);
}
}
return escapedTxt;
}
function alignDigits(buffer, digits, opts, force) {
if (buffer.length > 0 && digits > 0 && (!opts.digitsOptional || force)) {
var radixPosition = buffer.indexOf(opts.radixPoint), negationBack = false;
if (opts.negationSymbol.back === buffer[buffer.length - 1]) {
negationBack = true;
buffer.length--;
}
if (radixPosition === -1) {
buffer.push(opts.radixPoint);
radixPosition = buffer.length - 1;
}
for (var i = 1; i <= digits; i++) {
if (!isFinite(buffer[radixPosition + i])) {
buffer[radixPosition + i] = "0";
}
}
}
if (negationBack)
buffer.push(opts.negationSymbol.back);
return buffer;
}
function findValidator(symbol, maskset) {
var posNdx = 0;
if (symbol === "+") {
for (posNdx in maskset.validPositions) ;
posNdx = seekNext.call(this, parseInt(posNdx));
}
for (var tstNdx in maskset.tests) {
tstNdx = parseInt(tstNdx);
if (tstNdx >= posNdx) {
for (var ndx = 0, ndxl = maskset.tests[tstNdx].length; ndx < ndxl; ndx++) {
if ((maskset.validPositions[tstNdx] === undefined || symbol === "-") && maskset.tests[tstNdx][ndx].match.def === symbol) {
return tstNdx + ((maskset.validPositions[tstNdx] !== undefined && symbol !== "-") ? 1 : 0);
}
}
}
}
return posNdx;
}
function findValid(symbol, maskset) {
var ret = -1;
for (let ndx in maskset.validPositions) {
let tst = maskset.validPositions[ndx];
if (tst && tst.match.def === symbol) {
ret = parseInt(ndx);
break;
}
}
return ret;
}
function parseMinMaxOptions(opts) {
if (opts.parseMinMaxOptions === undefined) {
// convert min and max options
if (opts.min !== null) {
opts.min = opts.min.toString().replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
if (opts.radixPoint === ",") opts.min = opts.min.replace(opts.radixPoint, ".");
opts.min = isFinite(opts.min) ? parseFloat(opts.min) : NaN;
if (isNaN(opts.min)) opts.min = Number.MIN_VALUE;
}
if (opts.max !== null) {
opts.max = opts.max.toString().replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
if (opts.radixPoint === ",") opts.max = opts.max.replace(opts.radixPoint, ".");
opts.max = isFinite(opts.max) ? parseFloat(opts.max) : NaN;
if (isNaN(opts.max)) opts.max = Number.MAX_VALUE;
}
opts.parseMinMaxOptions = "done";
}
}
function genMask(opts) {
opts.repeat = 0;
//treat equal separator and radixpoint
if (opts.groupSeparator === opts.radixPoint && opts.digits && opts.digits !== "0") {
if (opts.radixPoint === ".") {
opts.groupSeparator = ",";
} else if (opts.radixPoint === ",") {
opts.groupSeparator = ".";
} else {
opts.groupSeparator = "";
}
}
//prevent conflict with default skipOptionalPartCharacter
if (opts.groupSeparator === " ") {
opts.skipOptionalPartCharacter = undefined;
}
//enforce placeholder to single
if (opts.placeholder.length > 1) {
opts.placeholder = opts.placeholder.charAt(0);
}
//only allow radixfocus when placeholder = 0
if (opts.positionCaretOnClick === "radixFocus" && opts.placeholder === "") {
opts.positionCaretOnClick = "lvp";
}
var decimalDef = "0", radixPointDef = opts.radixPoint;
if (opts.numericInput === true && opts.__financeInput === undefined) { //finance people input style
decimalDef = "1";
opts.positionCaretOnClick = opts.positionCaretOnClick === "radixFocus" ? "lvp" : opts.positionCaretOnClick;
opts.digitsOptional = false;
if (isNaN(opts.digits)) opts.digits = 2;
opts._radixDance = false;
radixPointDef = (opts.radixPoint === "," ? "?" : "!");
if (opts.radixPoint !== "" && opts.definitions[radixPointDef] === undefined) {
//update separator definition
opts.definitions[radixPointDef] = {};
opts.definitions[radixPointDef].validator = "[" + opts.radixPoint + "]";
opts.definitions[radixPointDef].placeholder = opts.radixPoint;
opts.definitions[radixPointDef].static = true;
opts.definitions[radixPointDef].generated = true; //forced marker as generated input
}
} else {
opts.__financeInput = false; //needed to keep original selection when remasking
opts.numericInput = true;
}
var mask = "[+]", altMask;
mask += autoEscape(opts.prefix, opts);
if (opts.groupSeparator !== "") {
if (opts.definitions[opts.groupSeparator] === undefined) {
//update separatot definition
opts.definitions[opts.groupSeparator] = {};
opts.definitions[opts.groupSeparator].validator = "[" + opts.groupSeparator + "]";
opts.definitions[opts.groupSeparator].placeholder = opts.groupSeparator;
opts.definitions[opts.groupSeparator].static = true;
opts.definitions[opts.groupSeparator].generated = true; //forced marker as generated input
}
mask += opts._mask(opts);
} else {
mask += "9{+}";
}
if (opts.digits !== undefined && opts.digits !== 0) {
var dq = opts.digits.toString().split(",");
if (isFinite(dq[0]) && dq[1] && isFinite(dq[1])) {
mask += radixPointDef + decimalDef + "{" + opts.digits + "}";
} else if (isNaN(opts.digits) || parseInt(opts.digits) > 0) {
if (opts.digitsOptional || opts.jitMasking) {
altMask = mask + radixPointDef + decimalDef + "{0," + opts.digits + "}";
// mask += "[" + opts.radixPoint + "]";
opts.keepStatic = true;
} else {
mask += radixPointDef + decimalDef + "{" + opts.digits + "}";
}
}
} else {
opts.inputmode = "numeric";
}
mask += autoEscape(opts.suffix, opts);
mask += "[-]";
if (altMask) {
mask = [(altMask + autoEscape(opts.suffix, opts) + "[-]"), mask];
}
opts.greedy = false; //enforce greedy false
parseMinMaxOptions(opts);
if (opts.radixPoint !== "")
opts.substitutes[opts.radixPoint == "." ? "," : "."] = opts.radixPoint;
// console.log(mask);
return mask;
}
function hanndleRadixDance(pos, c, radixPos, maskset, opts) {
if (opts._radixDance && opts.numericInput && c !== opts.negationSymbol.back) {
if (pos <= radixPos && (radixPos > 0 || c == opts.radixPoint) && (maskset.validPositions[pos - 1] === undefined || maskset.validPositions[pos - 1].input !== opts.negationSymbol.back)) {
pos -= 1;
}
}
return pos;
}
function decimalValidator(chrs, maskset, pos, strict, opts) {
var radixPos = maskset.buffer ? maskset.buffer.indexOf(opts.radixPoint) : -1,
result = (radixPos !== -1 || (strict && opts.jitMasking)) && new RegExp(opts.definitions["9"].validator).test(chrs);
if (opts._radixDance && radixPos !== -1 && result && maskset.validPositions[radixPos] == undefined) {
return {
insert: {
pos: radixPos === pos ? radixPos + 1 : radixPos,
c: opts.radixPoint
},
pos: pos
};
}
return result;
}
function checkForLeadingZeroes(buffer, opts) {
//check leading zeros
var numberMatches = new RegExp("(^" + (opts.negationSymbol.front !== "" ? escapeRegex(opts.negationSymbol.front) + "?" : "") + escapeRegex(opts.prefix) + ")(.*)(" + escapeRegex(opts.suffix) + (opts.negationSymbol.back != "" ? escapeRegex(opts.negationSymbol.back) + "?" : "") + "$)").exec(buffer.slice().reverse().join("")),
number = numberMatches ? numberMatches[2] : "", leadingzeroes = false;
if (number) {
number = number.split(opts.radixPoint.charAt(0))[0];
leadingzeroes = new RegExp("^[0" + opts.groupSeparator + "]*").exec(number);
}
return leadingzeroes && (leadingzeroes[0].length > 1 || leadingzeroes[0].length > 0 && leadingzeroes[0].length < number.length) ? leadingzeroes : false;
}
//number aliases
Inputmask.extendAliases({
"numeric": {
mask: genMask,
_mask: function (opts) {
return "(" + opts.groupSeparator + "999){+|1}";
},
digits: "*", //number of fractionalDigits
digitsOptional: true,
enforceDigitsOnBlur: false,
radixPoint: ".",
positionCaretOnClick: "radixFocus",
_radixDance: true,
groupSeparator: "",
allowMinus: true,
negationSymbol: {
front: "-", //"("
back: "" //")"
},
prefix: "",
suffix: "",
min: null, //minimum value
max: null, //maximum value
SetMaxOnOverflow: false,
step: 1,
inputType: "text", //number ~ specify that values which are set are in textform (radix point is same as in the options) or in numberform (radixpoint = .)
unmaskAsNumber: false,
roundingFN: Math.round, //Math.floor , fn(x)
inputmode: "decimal",
shortcuts: {k: "1000", m: "1000000"},
//global options
placeholder: "0",
greedy: false,
rightAlign: true,
insertMode: true,
autoUnmask: false,
skipOptionalPartCharacter: "",
usePrototypeDefinitions: false,
stripLeadingZeroes: true,
definitions: {
"0": {
validator: decimalValidator
},
"1": {
validator: decimalValidator,
definitionSymbol: "9"
},
"9": { //\uFF11-\uFF19 #1606
validator: "[0-9\uFF10-\uFF19\u0660-\u0669\u06F0-\u06F9]",
definitionSymbol: "*"
},
"+": {
validator: function (chrs, maskset, pos, strict, opts) {
return (opts.allowMinus && (chrs === "-" || chrs === opts.negationSymbol.front));
}
},
"-": {
validator: function (chrs, maskset, pos, strict, opts) {
return (opts.allowMinus && chrs === opts.negationSymbol.back);
}
}
},
preValidation: function (buffer, pos, c, isSelection, opts, maskset, caretPos, strict) {
const inputmask = this;
if (opts.__financeInput !== false && c === opts.radixPoint) return false;
var radixPos = buffer.indexOf(opts.radixPoint), initPos = pos;
pos = hanndleRadixDance(pos, c, radixPos, maskset, opts);
if (c === "-" || c === opts.negationSymbol.front) {
if (opts.allowMinus !== true) return false;
var isNegative = false,
front = findValid("+", maskset), back = findValid("-", maskset);
if (front !== -1) {
isNegative = [front, back];
}
return isNegative !== false ? {
remove: isNegative,
caret: initPos - opts.negationSymbol.back.length
} : {
insert: [
{
pos: findValidator.call(inputmask, "+", maskset),
c: opts.negationSymbol.front,
fromIsValid: true
},
{
pos: findValidator.call(inputmask, "-", maskset),
c: opts.negationSymbol.back,
fromIsValid: undefined
}],
caret: initPos + opts.negationSymbol.back.length
};
}
if (c === opts.groupSeparator) {
return {caret: initPos};
}
if (strict) return true;
if (radixPos !== -1 && (opts._radixDance === true && isSelection === false && c === opts.radixPoint && (opts.digits !== undefined && (isNaN(opts.digits) || parseInt(opts.digits) > 0)) && radixPos !== pos)) {
return {
"caret": opts._radixDance && pos === radixPos - 1 ? radixPos + 1 : radixPos
};
}
if (opts.__financeInput === false) {
if (isSelection) {
if (opts.digitsOptional) {
return {rewritePosition: caretPos.end};
} else if (!opts.digitsOptional) {
if (caretPos.begin > radixPos && caretPos.end <= radixPos) {
if (c === opts.radixPoint) {
return {
insert: {pos: radixPos + 1, c: "0", fromIsValid: true},
rewritePosition: radixPos
};
} else {
return {rewritePosition: radixPos + 1};
}
} else if (caretPos.begin < radixPos) {
return {rewritePosition: caretPos.begin - 1};
}
}
} else if (!opts.showMaskOnHover && !opts.showMaskOnFocus && !opts.digitsOptional && opts.digits > 0 && this.__valueGet.call(this.el) === "") {
return {rewritePosition: radixPos};
}
}
return {rewritePosition: pos};
},
postValidation: function (buffer, pos, c, currentResult, opts, maskset, strict) {
if (currentResult === false) return currentResult;
if (strict) return true;
if (opts.min !== null || opts.max !== null) {
var unmasked = opts.onUnMask(buffer.slice().reverse().join(""), undefined, $.extend({}, opts, {
unmaskAsNumber: true
}));
if (opts.min !== null && unmasked < opts.min && (unmasked.toString().length > opts.min.toString().length || unmasked < 0)) {
return false;
// return {
// refreshFromBuffer: true,
// buffer: alignDigits(opts.min.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
// };
}
if (opts.max !== null && unmasked > opts.max) {
return opts.SetMaxOnOverflow ? {
refreshFromBuffer: true,
buffer: alignDigits(opts.max.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
} : false;
}
}
return currentResult;
},
onUnMask: function (maskedValue, unmaskedValue, opts) {
if (unmaskedValue === "" && opts.nullable === true) {
return unmaskedValue;
}
var processValue = maskedValue.replace(opts.prefix, "");
processValue = processValue.replace(opts.suffix, "");
processValue = processValue.replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
if (opts.placeholder.charAt(0) !== "") {
processValue = processValue.replace(new RegExp(opts.placeholder.charAt(0), "g"), "0");
}
if (opts.unmaskAsNumber) {
if (opts.radixPoint !== "" && processValue.indexOf(opts.radixPoint) !== -1) processValue = processValue.replace(escapeRegex.call(this, opts.radixPoint), ".");
processValue = processValue.replace(new RegExp("^" + escapeRegex(opts.negationSymbol.front)), "-");
processValue = processValue.replace(new RegExp(escapeRegex(opts.negationSymbol.back) + "$"), "");
return Number(processValue);
}
return processValue;
}
,
isComplete: function (buffer, opts) {
var maskedValue = (opts.numericInput ? buffer.slice().reverse() : buffer).join("");
maskedValue = maskedValue.replace(new RegExp("^" + escapeRegex(opts.negationSymbol.front)), "-");
maskedValue = maskedValue.replace(new RegExp(escapeRegex(opts.negationSymbol.back) + "$"), "");
maskedValue = maskedValue.replace(opts.prefix, "");
maskedValue = maskedValue.replace(opts.suffix, "");
maskedValue = maskedValue.replace(new RegExp(escapeRegex(opts.groupSeparator) + "([0-9]{3})", "g"), "$1");
if (opts.radixPoint === ",") maskedValue = maskedValue.replace(escapeRegex(opts.radixPoint), ".");
return isFinite(maskedValue);
},
onBeforeMask: function (initialValue, opts) {
var radixPoint = opts.radixPoint || ",";
if (isFinite(opts.digits)) opts.digits = parseInt(opts.digits);
if ((typeof initialValue == "number" || opts.inputType === "number") && radixPoint !== "") {
initialValue = initialValue.toString().replace(".", radixPoint);
}
var isNagtive = initialValue.charAt(0) === "-" || initialValue.charAt(0) === opts.negationSymbol.front;
var valueParts = initialValue.split(radixPoint),
integerPart = valueParts[0].replace(/[^\-0-9]/g, ""),
decimalPart = valueParts.length > 1 ? valueParts[1].replace(/[^0-9]/g, "") : "",
forceDigits = valueParts.length > 1;
initialValue = integerPart + (decimalPart !== "" ? radixPoint + decimalPart : decimalPart);
var digits = 0;
if (radixPoint !== "") {
digits = !opts.digitsOptional ? opts.digits : (opts.digits < decimalPart.length ? opts.digits : decimalPart.length);
if (decimalPart !== "" || !opts.digitsOptional) {
var digitsFactor = Math.pow(10, digits || 1);
//make the initialValue a valid javascript number for the parsefloat
initialValue = initialValue.replace(escapeRegex(radixPoint), ".");
if (!isNaN(parseFloat(initialValue))) {
initialValue = (opts.roundingFN(parseFloat(initialValue) * digitsFactor) / digitsFactor).toFixed(digits);
}
initialValue = initialValue.toString().replace(".", radixPoint);
}
}
//this needs to be in a separate part and not directly in decimalPart to allow rounding
if (opts.digits === 0 && initialValue.indexOf(radixPoint) !== -1) {
initialValue = initialValue.substring(0, initialValue.indexOf(radixPoint));
}
if (opts.min !== null || opts.max !== null) {
var numberValue = initialValue.toString().replace(radixPoint, ".");
if (opts.min !== null && numberValue < opts.min) {
initialValue = opts.min.toString().replace(".", radixPoint);
} else if (opts.max !== null && numberValue > opts.max) {
initialValue = opts.max.toString().replace(".", radixPoint);
}
}
if (isNagtive && initialValue.charAt(0) !== "-") {
initialValue = "-" + initialValue;
}
return alignDigits(initialValue.toString().split(""), digits, opts, forceDigits).join("");
}
,
onBeforeWrite: function (e, buffer, caretPos, opts) {
function stripBuffer(buffer, stripRadix) {
if (opts.__financeInput !== false || stripRadix) {
var position = buffer.indexOf(opts.radixPoint);
if (position !== -1) {
buffer.splice(position, 1);
}
}
if (opts.groupSeparator !== "") {
while ((position = buffer.indexOf(opts.groupSeparator)) !== -1) {
buffer.splice(position, 1);
}
}
return buffer;
}
let result, leadingzeroes;
if (opts.stripLeadingZeroes && (leadingzeroes = checkForLeadingZeroes(buffer, opts))) {
const caretNdx = buffer.join("").lastIndexOf(leadingzeroes[0].split("").reverse().join("")) - (leadingzeroes[0] == leadingzeroes.input ? 0 : 1),
offset = (leadingzeroes[0] == leadingzeroes.input ? 1 : 0);
for (let i = leadingzeroes[0].length - offset; i > 0; i--) {
delete this.maskset.validPositions[caretNdx + i];
delete buffer[caretNdx + i];
}
}
if (e) {
switch (e.type) {
case "blur":
case "checkval":
if (opts.min !== null) {
var unmasked = opts.onUnMask(buffer.slice().reverse().join(""), undefined, $.extend({}, opts, {
unmaskAsNumber: true
}));
if (opts.min !== null && unmasked < opts.min) {
return {
refreshFromBuffer: true,
buffer: alignDigits(opts.min.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
};
}
}
if (buffer[buffer.length - 1] === opts.negationSymbol.front) { //strip negation symbol on blur when value is 0
var nmbrMtchs = new RegExp("(^" + (opts.negationSymbol.front != "" ? escapeRegex(opts.negationSymbol.front) + "?" : "") + escapeRegex(opts.prefix) + ")(.*)(" + escapeRegex(opts.suffix) + (opts.negationSymbol.back != "" ? escapeRegex(opts.negationSymbol.back) + "?" : "") + "$)").exec(stripBuffer(buffer.slice(), true).reverse().join("")),
number = nmbrMtchs ? nmbrMtchs[2] : "";
if (number == 0) {
result = {refreshFromBuffer: true, buffer: [0]};
}
} else if (opts.radixPoint !== "") { //strip radixpoint on blur when it is the latest char
var radixNDX = buffer.indexOf(opts.radixPoint);
if (radixNDX === opts.suffix.length) {
if (result && result.buffer) {
result.buffer.splice(0, 1 + opts.suffix.length);
} else {
buffer.splice(0, 1 + opts.suffix.length);
result =
{refreshFromBuffer: true, buffer: stripBuffer(buffer)};
}
}
}
if (opts.enforceDigitsOnBlur) {
result = result || {};
var bffr = (result && result.buffer) || buffer.slice().reverse();
result.refreshFromBuffer = true;
result.buffer = alignDigits(bffr, opts.digits, opts, true).reverse();
}
}
}
return result;
},
onKeyDown: function (e, buffer, caretPos, opts) {
var $input = $(this), bffr;
var pattern, c = String.fromCharCode(e.keyCode).toLowerCase();
if ((pattern = (opts.shortcuts && opts.shortcuts[c]))) {
if (pattern.length > 1) {
this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) * parseInt(pattern));
$input.trigger("setvalue");
return false;
}
}
if (e.ctrlKey) {
switch (e.keyCode) {
case keyCode.UP:
this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) + parseInt(opts.step));
$input.trigger("setvalue");
return false;
case keyCode.DOWN:
this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) - parseInt(opts.step));
$input.trigger("setvalue");
return false;
}
}
if (!e.shiftKey && (e.keyCode === keyCode.DELETE || e.keyCode === keyCode.BACKSPACE || e.keyCode === keyCode.BACKSPACE_SAFARI) && caretPos.begin !== buffer.length) {
if (buffer[e.keyCode === keyCode.DELETE ? caretPos.begin - 1 : caretPos.end] === opts.negationSymbol.front) {
bffr = buffer.slice().reverse();
if (opts.negationSymbol.front !== "") bffr.shift();
if (opts.negationSymbol.back !== "") bffr.pop();
$input.trigger("setvalue", [bffr.join(""), caretPos.begin]);
return false;
} else if (opts._radixDance === true) {
var radixPos = buffer.indexOf(opts.radixPoint);
if (!opts.digitsOptional) {
if (radixPos !== -1 && (caretPos.begin < radixPos || caretPos.end < radixPos || (e.keyCode === keyCode.DELETE && caretPos.begin === radixPos))) {
if (caretPos.begin === caretPos.end && (e.keyCode === keyCode.BACKSPACE || e.keyCode === keyCode.BACKSPACE_SAFARI)) { //only adjust when not a selection
caretPos.begin++;
}
bffr = buffer.slice().reverse();
bffr.splice(bffr.length - caretPos.begin, caretPos.begin - caretPos.end + 1);
// console.log(caretPos);
bffr = alignDigits(bffr, opts.digits, opts).join("");
$input.trigger("setvalue", [bffr, caretPos.begin >= bffr.length ? radixPos + 1 : caretPos.begin]);
return false;
}
} else if (radixPos === 0) {
bffr = buffer.slice().reverse();
bffr.pop();
$input.trigger("setvalue", [bffr.join(""), caretPos.begin >= bffr.length ? bffr.length : caretPos.begin]);
return false;
}
}
}
}
},
"currency": {
prefix: "", //"$ ",
groupSeparator: ",",
alias: "numeric",
digits: 2,
digitsOptional: false
},
"decimal": {
alias: "numeric"
},
"integer": {
alias: "numeric",
inputmode: "numeric",
digits: 0
},
"percentage": {
alias: "numeric",
min: 0,
max: 100,
suffix: " %",
digits: 0,
allowMinus: false
},
"indianns": { //indian numbering system
alias: "numeric",
_mask: function (opts) {
return "(" + opts.groupSeparator + "99){*|1}(" + opts.groupSeparator + "999){1|1}";
},
groupSeparator: ",",
radixPoint: ".",
placeholder: "0",
digits: 2,
digitsOptional: false
}
});