Browse Source

Merge branch '2.x' into 2.5

Robin Herbots 12 years ago
parent
commit
0e55ed9e85
5 changed files with 117 additions and 57 deletions
  1. 25 1
      README.md
  2. 1 1
      build.properties
  3. 1 1
      jquery.inputmask.jquery.json
  4. 70 54
      js/jquery.inputmask.js
  5. 20 0
      qunit/tests.js

+ 25 - 1
README.md

@@ -22,7 +22,7 @@ Highlights:
 - support data-inputmask attribute  
 - support data-inputmask attribute  
 - multi-mask support  
 - multi-mask support  
 - regex-mask support
 - regex-mask support
-- value formatting without input element
+- value formatting / validating without input element
 
 
 Demo page see http://robinherbots.github.io/jquery.inputmask
 Demo page see http://robinherbots.github.io/jquery.inputmask
 
 
@@ -476,6 +476,22 @@ $(document).ready(function(){
 });
 });
 ```
 ```
 
 
+### onBeforeMask
+
+This callback allows for preprocessing the initial value before actually handling the value for masking.  This can be usefull for stripping away some characters before processing.
+
+```javascript
+$(document).ready(function(){
+   $("#test").inputmask("99.", {
+                repeat: 4,
+                onBeforeMask: function (initialValue) {
+                    //do somehing with the value
+                    return initialValue;
+                }
+            });
+});
+```
+
 ### hasMaskedValue
 ### hasMaskedValue
 
 
 Check whether the returned value is masked or not; currently only works reliably when using jquery.val fn to retrieve the value 
 Check whether the returned value is masked or not; currently only works reliably when using jquery.val fn to retrieve the value 
@@ -591,6 +607,14 @@ Think of formatting values to show in jqGrid or on other elements then inputs.
 var formattedDate = $.inputmask.format("2331973", { alias: "dd/mm/yyyy"});
 var formattedDate = $.inputmask.format("2331973", { alias: "dd/mm/yyyy"});
 ```
 ```
 
 
+## Value validating
+
+Validate a given value against the mask.
+
+```javascript
+var isValid = $.inputmask.isValid("23/03/1973", { alias: "dd/mm/yyyy"});
+```
+
 ## Compiling with Google Closure Compiler
 ## Compiling with Google Closure Compiler
 
 
 First grab the sources from GitHub.  In the root you type ant.
 First grab the sources from GitHub.  In the root you type ant.

+ 1 - 1
build.properties

@@ -7,7 +7,7 @@ distdir = dist
 
 
 build.major = 2
 build.major = 2
 build.minor = 4
 build.minor = 4
-build.revision = 24
+build.revision = 27
 
 
 target = jquery.inputmask.bundle.js
 target = jquery.inputmask.bundle.js
 target.min = jquery.inputmask.bundle.min.js
 target.min = jquery.inputmask.bundle.min.js

+ 1 - 1
jquery.inputmask.jquery.json

@@ -8,7 +8,7 @@
 		"inputmask",
 		"inputmask",
 		"mask"
 		"mask"
     ],
     ],
-    "version": "2.4.24",
+    "version": "2.4.27",
     "author": {
     "author": {
         "name": "Robin Herbots",
         "name": "Robin Herbots",
         "url": "http://github.com/RobinHerbots/jquery.inputmask"
         "url": "http://github.com/RobinHerbots/jquery.inputmask"

+ 70 - 54
js/jquery.inputmask.js

@@ -230,16 +230,13 @@
             iphone = navigator.userAgent.match(new RegExp("iphone", "i")) !== null,
             iphone = navigator.userAgent.match(new RegExp("iphone", "i")) !== null,
             android = navigator.userAgent.match(new RegExp("android.*safari.*", "i")) !== null,
             android = navigator.userAgent.match(new RegExp("android.*safari.*", "i")) !== null,
             androidchrome = navigator.userAgent.match(new RegExp("android.*chrome.*", "i")) !== null,
             androidchrome = navigator.userAgent.match(new RegExp("android.*chrome.*", "i")) !== null,
-            pasteEvent = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange",
-            androidchrome32 = false, androidchrome18 = false, androidchrome29 = false;
-
-        if (androidchrome) {
-            var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
-                version = parseInt(new RegExp(/[0-9]+/).exec(browser));
-            androidchrome32 = (version == 32);
-            androidchrome18 = (version == 18);
-            androidchrome29 = (version == 29);
-        }
+            pasteEvent = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
+
+        //if (androidchrome) {
+        //    var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
+        //        version = parseInt(new RegExp(/[0-9]+/).exec(browser));
+        //    androidchrome32 = (version == 32);
+        //}
 
 
         //masking scope
         //masking scope
         //actionObj definition see below
         //actionObj definition see below
@@ -709,6 +706,38 @@
             }
             }
 
 
             function patchValueProperty(npt) {
             function patchValueProperty(npt) {
+                function PatchValhook(type) {
+                    if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
+                        var valueGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) { return elem.value; };
+                        var valueSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
+                            elem.value = value;
+                            return elem;
+                        };
+
+                        $.valHooks[type] = {
+                            get: function (elem) {
+                                var $elem = $(elem);
+                                if ($elem.data('_inputmask')) {
+                                    if ($elem.data('_inputmask')['opts'].autoUnmask)
+                                        return $elem.inputmask('unmaskedvalue');
+                                    else {
+                                        var result = valueGet(elem),
+                                            inputData = $elem.data('_inputmask'), masksets = inputData['masksets'],
+                                            activeMasksetIndex = inputData['activeMasksetIndex'];
+                                        return result != masksets[activeMasksetIndex]['_buffer'].join('') ? result : '';
+                                    }
+                                } else return valueGet(elem);
+                            },
+                            set: function (elem, value) {
+                                var $elem = $(elem);
+                                var result = valueSet(elem, value);
+                                if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask');
+                                return result;
+                            },
+                            inputmaskpatch: true
+                        };
+                    }
+                }
                 var valueProperty;
                 var valueProperty;
                 if (Object.getOwnPropertyDescriptor)
                 if (Object.getOwnPropertyDescriptor)
                     valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
                     valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
@@ -761,43 +790,11 @@
                         npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
                         npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
                         npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
                         npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
                     }
                     }
-                    if ($.valHooks.text == undefined || $.valHooks.text.inputmaskpatch != true) {
-                        var valueGet = $.valHooks.text && $.valHooks.text.get ? $.valHooks.text.get : function (elem) { return elem.value; };
-                        var valueSet = $.valHooks.text && $.valHooks.text.set ? $.valHooks.text.set : function (elem, value) {
-                            elem.value = value;
-                            return elem;
-                        };
-
-                        jQuery.extend($.valHooks, {
-                            text: {
-                                get: function (elem) {
-                                    var $elem = $(elem);
-                                    if ($elem.data('_inputmask')) {
-                                        if ($elem.data('_inputmask')['opts'].autoUnmask)
-                                            return $elem.inputmask('unmaskedvalue');
-                                        else {
-                                            var result = valueGet(elem),
-                                                inputData = $elem.data('_inputmask'), masksets = inputData['masksets'],
-                                                activeMasksetIndex = inputData['activeMasksetIndex'];
-                                            return result != masksets[activeMasksetIndex]['_buffer'].join('') ? result : '';
-                                        }
-                                    } else return valueGet(elem);
-                                },
-                                set: function (elem, value) {
-                                    var $elem = $(elem);
-                                    var result = valueSet(elem, value);
-                                    if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask');
-                                    return result;
-                                },
-                                inputmaskpatch: true
-                            }
-                        });
-                    }
+                    PatchValhook(npt.type);
                 }
                 }
             }
             }
 
 
             //shift chars to left from start to end and put c at end position if defined
             //shift chars to left from start to end and put c at end position if defined
-
             function shiftL(start, end, c, maskJumps) {
             function shiftL(start, end, c, maskJumps) {
                 var buffer = getActiveBuffer();
                 var buffer = getActiveBuffer();
                 if (maskJumps !== false) //jumping over nonmask position
                 if (maskJumps !== false) //jumping over nonmask position
@@ -1185,14 +1182,11 @@
                 //backspace in chrome32 only fires input event - detect & treat
                 //backspace in chrome32 only fires input event - detect & treat
                 var caretPos = caret(input),
                 var caretPos = caret(input),
                     currentValue = input._valueGet();
                     currentValue = input._valueGet();
-
-                console.log(currentValue);
-
-                if (currentValue.charAt(caretPos.begin) != getActiveBuffer()[caretPos.begin] 
-              	  	&& currentValue.charAt(caretPos.begin + 1) != getActiveBuffer()[caretPos.begin] 
-                	&& !isMask(caretPos.begin)) {
-                    	e.keyCode = opts.keyCode.BACKSPACE;
-                    	keydownEvent.call(input, e);
+                if (currentValue.charAt(caretPos.begin) != getActiveBuffer()[caretPos.begin]
+                    && currentValue.charAt(caretPos.begin + 1) != getActiveBuffer()[caretPos.begin]
+                    && !isMask(caretPos.begin)) {
+                    e.keyCode = opts.keyCode.BACKSPACE;
+                    keydownEvent.call(input, e);
                 } else { //nonnumerics don't fire keypress 
                 } else { //nonnumerics don't fire keypress 
                     checkVal(input, false, false);
                     checkVal(input, false, false);
                     writeBuffer(input, getActiveBuffer());
                     writeBuffer(input, getActiveBuffer());
@@ -1391,14 +1385,15 @@
                          ).bind("keypress.inputmask", keypressEvent
                          ).bind("keypress.inputmask", keypressEvent
                          ).bind("keyup.inputmask", keyupEvent);
                          ).bind("keyup.inputmask", keyupEvent);
 
 
-                    if (androidchrome32 || androidchrome18 || androidchrome29) {
+                    if (androidchrome) {
                         $el.bind("input.inputmask", chromeInputEvent);
                         $el.bind("input.inputmask", chromeInputEvent);
-                    }    
+                    }
                     if (msie1x)
                     if (msie1x)
                         $el.bind("input.inputmask", inputEvent);
                         $el.bind("input.inputmask", inputEvent);
 
 
                     //apply mask
                     //apply mask
-                    checkVal(el, true, false);
+                    var initialValue = opts.onBeforeMask != undefined ? opts.onBeforeMask.call(this, input._valueGet()) : input._valueGet();
+                    checkVal(el, true, false, initialValue.split(''));
                     valueOnFocus = getActiveBuffer().join('');
                     valueOnFocus = getActiveBuffer().join('');
                     // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
                     // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
                     var activeElement;
                     var activeElement;
@@ -1449,6 +1444,21 @@
 
 
                         checkVal($el, false, false, actionObj["value"].split(''), true);
                         checkVal($el, false, false, actionObj["value"].split(''), true);
                         return getActiveBuffer().join('');
                         return getActiveBuffer().join('');
+                    case "isValid":
+                        $el = $({});
+                        $el.data('_inputmask', {
+                            'masksets': masksets,
+                            'activeMasksetIndex': activeMasksetIndex,
+                            'opts': opts,
+                            'isRTL': opts.numericInput
+                        });
+                        if (opts.numericInput) {
+                            opts.isNumeric = opts.numericInput;
+                            isRTL = true;
+                        }
+
+                        checkVal($el, false, true, actionObj["value"].split(''));
+                        return isComplete(getActiveBuffer());
                 }
                 }
             }
             }
         };
         };
@@ -1474,6 +1484,7 @@
                 aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
                 aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
                 onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
                 onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
                 onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
                 onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
+                onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value.  args => initialValue => return processedValue
                 onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value.  args => pastedValue => return processedValue
                 onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value.  args => pastedValue => return processedValue
                 onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue.  args => maskedValue, unmaskedValue
                 onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue.  args => maskedValue, unmaskedValue
                 showMaskOnFocus: true, //show the mask-placeholder when the input has focus
                 showMaskOnFocus: true, //show the mask-placeholder when the input has focus
@@ -1530,6 +1541,11 @@
                 var opts = $.extend(true, {}, $.inputmask.defaults, options);
                 var opts = $.extend(true, {}, $.inputmask.defaults, options);
                 resolveAlias(opts.alias, options, opts);
                 resolveAlias(opts.alias, options, opts);
                 return maskScope(generateMaskSets(opts), 0, opts, { "action": "format", "value": value });
                 return maskScope(generateMaskSets(opts), 0, opts, { "action": "format", "value": value });
+            },
+            isValid: function (value, options) {
+                var opts = $.extend(true, {}, $.inputmask.defaults, options);
+                resolveAlias(opts.alias, options, opts);
+                return maskScope(generateMaskSets(opts), 0, opts, { "action": "isValid", "value": value });
             }
             }
         };
         };
 
 

+ 20 - 0
qunit/tests.js

@@ -480,6 +480,15 @@ test("inputmask(\"mm/yyyy\") ~ .val(\"031973\") - disabled input", function () {
     $("#testmask").remove();
     $("#testmask").remove();
 });
 });
 
 
+test("inputmask({ \"mask\": \"(999) 999-9999\" }) ~ .val(\"8144419449\") - type=\"tel\" - bodrick", function () {
+    $('body').append('<input type="tel" id="testmask" disabled="disabled" />');
+    $("#testmask").inputmask({ "mask": "(999) 999-9999" });
+    $("#testmask").val("8144419449");
+    equal($("#testmask").val(), "(814) 441-9449", "Result " + $("#testmask").val());
+
+    $("#testmask").remove();
+});
+
 module("Optional & multi masks");
 module("Optional & multi masks");
 test("inputmask(\"(99) 9999[9]-99999\") - input 121234-12345", function () {
 test("inputmask(\"(99) 9999[9]-99999\") - input 121234-12345", function () {
     $('body').append('<input type="text" id="testmask" />');
     $('body').append('<input type="text" id="testmask" />');
@@ -1749,6 +1758,17 @@ test("$.inputmask.format(\"016501030020001DE1015170\", { mask: \"99 999 999 999
     equal(formattedValue, "01 650 103 002 0001 DE101 5170", "Result " + formattedValue);
     equal(formattedValue, "01 650 103 002 0001 DE101 5170", "Result " + formattedValue);
 });
 });
 
 
+module("Value Validating");
+test("$.inputmask.isValid(\"23/03/1973\", { alias: \"date\"})", function () {
+    var formattedValue = $.inputmask.isValid("23/03/1973", { alias: "date" });
+    equal(formattedValue, true, "Result " + formattedValue);
+});
+
+test("$.inputmask.isValid(\"01 650 103 002 0001 DE101 5170\", { mask: \"99 999 999 999 9999 \\D\\E*** 9999\"})", function () {
+    var formattedValue = $.inputmask.isValid("01 650 103 002 0001 DE101 5170", { mask: "99 999 999 999 9999 \\D\\E*** 9999" });
+    equal(formattedValue, true, "Result " + formattedValue);
+});
+
 module("Dynamic Masks");
 module("Dynamic Masks");
 test("inputmask(\"*{1,20}@*{1,20}.*{2,6}[.*{2}]\" - email mask", function () {
 test("inputmask(\"*{1,20}@*{1,20}.*{2,6}[.*{2}]\" - email mask", function () {
     $('body').append('<input type="text" id="testmask" />');
     $('body').append('<input type="text" id="testmask" />');