From b95e234a1e97c2f0f6398d52e2f79c3a1ab54e1b Mon Sep 17 00:00:00 2001 From: obuligan Date: Mon, 2 Jun 2014 11:37:40 +0300 Subject: [PATCH] allow specifying converters (see Typing.Spec.js for test case and usage) --- spec/Typing.Spec.js | 21 ++++++++++++++++++++- src/jquery.maskedinput.js | 16 +++++++++++++--- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/spec/Typing.Spec.js b/spec/Typing.Spec.js index 8fbf155..c369377 100644 --- a/spec/Typing.Spec.js +++ b/spec/Typing.Spec.js @@ -53,6 +53,25 @@ describe("Typing Specifications", function() { expect(caret.begin).toEqual(1); expect(caret.end).toEqual(1); }); - }); + }); + + describe("when there are converters in place apply converters at each typing ",function(){ + beforeEach(function(){ + runs(function(){ + input + .mask("a/a",{converters:{'a':function(c){return c.toUpperCase();}}}) + .focus() + }); + waits(1); + runs(function(){ + input + .mashKeys("e") + .mashKeys("e") + }); + }) + it("should apply converter (converter is just c.toUpperCase())",function(){ + expect(input).toHaveValue("E/E"); + }); + }); }); }); \ No newline at end of file diff --git a/src/jquery.maskedinput.js b/src/jquery.maskedinput.js index ad999e3..e0c55ec 100644 --- a/src/jquery.maskedinput.js +++ b/src/jquery.maskedinput.js @@ -23,7 +23,8 @@ $.mask = { }, autoclear: true, dataName: "rawMaskFn", - placeholder: '_' + placeholder: '_', + converters: {} }; $.fn.extend({ @@ -78,25 +79,29 @@ $.fn.extend({ settings = $.extend({ autoclear: $.mask.autoclear, placeholder: $.mask.placeholder, // Load default placeholder + converters: $.mask.converters, completed: null }, settings); defs = $.mask.definitions; tests = []; + converters = []; partialPosition = len = mask.length; firstNonMaskPos = null; - + $.each(mask.split(""), function(i, c) { if (c == '?') { len--; partialPosition = i; } else if (defs[c]) { tests.push(new RegExp(defs[c])); + converters.push(settings.converters[c]); if (firstNonMaskPos === null) { firstNonMaskPos = tests.length - 1; } } else { + converters.push(null); tests.push(null); } }); @@ -239,6 +244,7 @@ $.fn.extend({ if (p < len) { c = String.fromCharCode(k); if (tests[p].test(c)) { + c = applyConverter(c,p); shiftR(p); buffer[p] = c; @@ -276,6 +282,10 @@ $.fn.extend({ function writeBuffer() { input.val(buffer.join('')); } + function applyConverter(c,testIndex){ + if(converters[testIndex]) return converters[testIndex].call(this,c) + return c; + } function checkVal(allow) { //try to place characters where they belong var test = input.val(), @@ -283,13 +293,13 @@ $.fn.extend({ i, c, pos; - for (i = 0, pos = 0; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; while (pos++ < test.length) { c = test.charAt(pos - 1); if (tests[i].test(c)) { + c = applyConverter(c,i); buffer[i] = c; lastMatch = i; break;