2
0
mirror of https://github.com/tenrok/maska.git synced 2026-06-05 16:42:28 +03:00

#51 Added value preprocessor

This commit is contained in:
Yury Mamedov
2021-11-10 00:40:25 +03:00
parent 9676906225
commit d3f1a7b582
9 changed files with 23 additions and 9 deletions
+2 -1
View File
@@ -7,6 +7,7 @@ function getOpts (mask) {
if (mask.mask) {
opts.mask = Array.isArray(mask.mask) ? JSON.stringify(mask.mask) : mask.mask
opts.tokens = mask.tokens ? { ...mask.tokens } : {}
opts.preprocessor = mask.preprocessor;
} else {
opts.mask = Array.isArray(mask) ? JSON.stringify(mask) : mask
}
@@ -31,7 +32,7 @@ const directive = () => {
if (state.has(el) && !needUpdate(mask)) {
return
}
state.set(el, new Maska(el, getOpts(mask.value)))
}
}
+14 -2
View File
@@ -6,6 +6,10 @@ export default class Maska {
constructor (el, opts = {}) {
if (!el) throw new Error('Maska: no element for mask')
if (opts.preprocessor != null && typeof opts.preprocessor != 'function') {
throw new Error('Maska: preprocessor must be a function')
}
if (opts.tokens) {
for (const i in opts.tokens) {
opts.tokens[i] = { ...opts.tokens[i] }
@@ -15,9 +19,11 @@ export default class Maska {
}
}
this._opts = {
mask: opts.mask,
tokens: { ...tokens, ...opts.tokens }
tokens: { ...tokens, ...opts.tokens },
preprocessor: opts.preprocessor
}
this._el = isString(el) ? document.querySelectorAll(el) : !el.length ? [el] : el
this.inputEvent = (e) => this.updateValue(e.target, e)
@@ -65,7 +71,13 @@ export default class Maska {
const digit = oldValue[position - 1]
el.dataset.maskRawValue = mask(el.value, el.dataset.mask, this._opts.tokens, false)
el.value = mask(el.value, el.dataset.mask, this._opts.tokens)
let elValue = el.value;
if (this._opts.preprocessor) {
elValue = this._opts.preprocessor(elValue);
}
el.value = mask(elValue, el.dataset.mask, this._opts.tokens)
if (evt && evt.inputType === 'insertText' && position === oldValue.length) {
position = el.value.length