diff --git a/.gitignore b/.gitignore
index bfa0621..9bbba37 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,6 @@
.idea/*
+
+node_modules/
+bower_components/
+dist/
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..562a78b
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,6 @@
+language: node_js
+node_js:
+ - "0.10"
+before_script:
+ - npm install -g grunt-cli
+
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..9e4605b
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,127 @@
+# Contributing
+
+Please take a moment to review this document in order to make the contribution
+process easy and effective for everyone involved!
+
+## Using the issue tracker
+
+The issue tracker is for:
+* [Bug Reports](#bug-reports)
+* [Feature Requests](#feature-requests)
+* [Submitting Pull Requests](#pull-requests)
+
+Please **do not** use the issue tracker for personal support requests.
+
+## Bug Reports
+
+A bug is a _demonstrable problem_ that is caused by the code in the repository.
+
+Guidelines for bug reports:
+
+1. **Use the GitHub issue search** — check if the issue has already been
+ reported.
+
+2. **Check if the issue has been fixed** — try to reproduce it using the
+ `master` branch in the repository.
+
+3. **Isolate and report the problem** — ideally create a reduced test
+ case or a small [jsfiddle](http://jsfiddle.net) showing the issue.
+
+Please try to be as detailed as possible in your report. Include information about
+your operating system, browser, jQuery version, and masked input plugin version.
+Please provide steps to reproduce the issue as well as the outcome you were expecting.
+
+## Feature Requests
+
+Feature requests are welcome. It's up to *you* to make a strong case of the merits of
+this feature. Please provide as much detail and context as possible.
+
+Features that have a very narrow use case are unlikely to be accepted unless we
+can come up with a way to come to a more general solution. Please don't let
+that stop you from sharing your ideas, just keep that in mind.
+
+## Pull Requests
+
+Good pull requests are very helpful. They should remain focused
+in scope and avoid containing unrelated commits.
+
+**IMPORTANT**: By submitting a patch, you agree that your work will be
+licensed under the license used by the project.
+
+If you have any large pull request in mind (e.g. implementing features,
+refactoring code, etc), **please ask first** otherwise you risk spending
+a lot of time working on something that the project's developers might
+not want to merge into the project.
+
+Please adhere to the coding conventions in the project (indentation,
+accurate comments, etc.) and don't forget to add your own tests and
+documentation. When working with git, we recommend the following process
+in order to craft an excellent pull request:
+
+1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork,
+ and configure the remotes:
+
+ ```bash
+ # Clone your fork of the repo into the current directory
+ git clone https://github.com//jquery.maskedinput
+ # Navigate to the newly cloned directory
+ cd jquery.maskedinput
+ # Assign the original repo to a remote called "upstream"
+ git remote add upstream https://github.com/digitalBush/jquery.maskedinput
+ ```
+
+2. If you cloned a while ago, get the latest changes from upstream:
+
+ ```bash
+ git checkout master
+ git pull upstream master
+ ```
+
+3. Create a new topic branch (off of `master`) to contain your feature, change,
+ or fix.
+
+ **IMPORTANT**: Making changes in `master` is discouraged. You should always
+ keep your local `master` in sync with upstream `master` and make your
+ changes in topic branches.
+
+ ```bash
+ git checkout -b
+ ```
+
+4. Commit your changes in logical chunks. Keep your commit messages organized,
+ with a short description in the first line and more detailed information on
+ the following lines.
+
+ Please use git's
+ [interactive rebase](https://help.github.com/articles/interactive-rebase)
+ feature to tidy up your commits before making them public. Ideally when you
+ are finished you'll have a single commit.
+
+5. Make sure all the tests are still passing.
+
+ ```bash
+ npm test
+ ```
+
+6. Push your topic branch up to your fork:
+
+ ```bash
+ git push origin
+ ```
+
+7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
+ with a clear title and description.
+
+8. If you haven't updated your pull request for a while, you should consider
+ rebasing on master and resolving any conflicts.
+
+ **IMPORTANT**: _Never ever_ merge upstream `master` into your branches. You
+ should always `git rebase` on `master` to bring your changes up to date when
+ necessary.
+
+ ```bash
+ git checkout master
+ git pull upstream master
+ git checkout
+ git rebase master
+ ```
diff --git a/Jakefile b/Jakefile
deleted file mode 100644
index 5001cb7..0000000
--- a/Jakefile
+++ /dev/null
@@ -1,31 +0,0 @@
-var Handlebars=require("handlebars"),
- fs = require("fs"),
- path = require ("path"),
- UglifyJS = require("uglify-js"),
- distPath='dist/';
-
-Handlebars.registerHelper('include', function(context) {
- return fs.readFileSync(context,'utf8');
-});
-
-function keepComment(node,comment){
- return comment.type === "comment2";
-}
-
-task('clean',function(){
- fs.rmdir(distPath)
-});
-
-task('default',['clean'], function (params) {
- fs.mkdir(distPath,0755);
-
- var options = JSON.parse(fs.readFileSync('plugin.json','utf8'))
- options.Year=new Date().getFullYear()
-
- var template = Handlebars.compile(fs.readFileSync('templates/jquery.maskedinput.template','utf8'));
- var debugFile = path.join(distPath,'jquery.maskedinput.js');
- fs.writeFileSync(debugFile,template(options));
-
- compressed = UglifyJS.minify(debugFile,{output:{comments:keepComment}});
- fs.writeFileSync(path.join(distPath,'jquery.maskedinput.min.js'), compressed.code);
-});
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
index 8f4ccae..e6114e8 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2007-2013 Josh Bush (digitalbush.com)
+Copyright (c) 2007-2015 Josh Bush (digitalbush.com)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
@@ -19,4 +19,4 @@ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
+OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
index ef6f39b..87889b9 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,11 @@
Masked Input Plugin for jQuery
==============================
+**Notice: This project is no longer being maintained.**
+
+I started this project [over 10 years ago](https://forum.jquery.com/topic/jquery-introduction-and-masked-input-plugin) to fill a need for a side project I was working on at the time. Nothing ever became of that side project, but this little plugin lived on. Over the years it brought me joy to stumble on sites using this thing. It was super encouraging to hear from people using it in their own products. I tried for a while to maintain it, even after I had moved away from front end web development.
+
+The time has come to officially call it quits. The web has changed(**A LOT**) and there are better things out there like [Cleave.js](https://nosir.github.io/cleave.js/). I'll leave this repo up for posterity in an archived state. Thank you to everyone who contributed to or used this plugin over the years.
+
Overview
--------
@@ -9,7 +15,94 @@ This is a masked input plugin for the jQuery javascript library. It allows a use
* 9 - Represents a numeric character (0-9)
* \* - Represents an alphanumeric character (A-Z,a-z,0-9)
-If your requirements aren't met by the predefined placeholders, you can always add your own. For example, maybe you need a mask to only allow hexadecimal characters. You can add your own definition for a placeholder, say 'h', like so: `$.mask.definitions['h'] = "[A-Fa-f0-9]";` Then you can use that to mask for something like css colors in hex with a mask "#hhhhhh".
+### Usage
+First, include the jQuery and masked input javascript files.
+
+```html
+
+
+```
+
+Next, call the mask function for those items you wish to have masked.
+
+```html
+jQuery(function($){
+ $("#date").mask("99/99/9999");
+ $("#phone").mask("(999) 999-9999");
+ $("#tin").mask("99-9999999");
+ $("#ssn").mask("999-99-9999");
+});
+```
+
+Optionally, if you are not satisfied with the underscore ('_') character as a placeholder, you may pass an optional argument to the maskedinput method.
+
+```html
+jQuery(function($){
+ $("#product").mask("99/99/9999",{placeholder:" "});
+});
+```
+
+Optionally, if you would like to execute a function once the mask has been completed, you can specify that function as an optional argument to the maskedinput method.
+
+```html
+jQuery(function($){
+ $("#product").mask("99/99/9999",{completed:function(){alert("You typed the following: "+this.val());}});
+});
+```
+
+Optionally, if you would like to disable the automatic discarding of the uncomplete input, you may pass an optional argument to the maskedinput method
+```html
+jQuery(function($){
+ $("#product").mask("99/99/9999",{autoclear: false});
+});
+```
+
+You can now supply your own mask definitions.
+```html
+jQuery(function($){
+ $.mask.definitions['~']='[+-]';
+ $("#eyescript").mask("~9.99 ~9.99 999");
+});
+```
+
+You can have part of your mask be optional. Anything listed after '?' within the mask is considered optional user input. The common example for this is phone number + optional extension.
+
+```html
+jQuery(function($){
+ $("#phone").mask("(999) 999-9999? x99999");
+});
+```
+
+If your requirements aren't met by the predefined placeholders, you can always add your own. For example, maybe you need a mask to only allow hexadecimal characters. You can add your own definition for a placeholder, say 'h', like so: `$.mask.definitions['h'] = "[A-Fa-f0-9]";` Then you can use that to mask for something like css colors in hex with a `mask "#hhhhhh"`.
+
+```html
+jQuery(function($){
+ $("#phone").mask("#hhhhhh");
+});
+```
+
By design, this plugin will reject input which doesn't complete the mask. You can bypass this by using a '?' character at the position where you would like to consider input optional. For example, a mask of "(999) 999-9999? x99999" would require only the first 10 digits of a phone number with extension being optional.
+
+Getting the bits
+----------------
+We generally recommend that you use [bower](http://bower.io) to install jquery.maskedinput plugin.
+
+ $ bower install --save jquery.maskedinput
+
+
+Setting up your Developer Environment
+-------------------------------------
+jQuery Masked Input uses [NodeJS](http://www.nodejs.org) and [GruntJS](http://www.gruntjs.com) as it's developer platform and build automation tool.
+
+To get your environment setup correctly, you'll need nodejs version 0.8.25 or greater installed. You'll also need to install the grunt command line tool:
+
+ $ sudo npm install -g grunt-cli
+
+Once node is installed on your system all that you need to do is install the developer dependencies and run the grunt build:
+
+ $ npm install
+ $ grunt
+
+All of the tests for jQuery Masked Input are run using the [jasmine](http://jasmine.github.io/) test runner.
diff --git a/bower.json b/bower.json
new file mode 100644
index 0000000..e6368cb
--- /dev/null
+++ b/bower.json
@@ -0,0 +1,29 @@
+{
+ "name": "jquery.maskedinput",
+ "homepage": "http://digitalbush.com/projects/masked-input-plugin/",
+ "authors": [
+ "Josh Bush (digitalbush.com)"
+ ],
+ "description": "jQuery Masked Input Plugin",
+ "main": "./dist/jquery.maskedinput.js",
+ "moduleType": [
+ "es6"
+ ],
+ "keywords": [
+ "input",
+ "form",
+ "mask",
+ "jquery"
+ ],
+ "license": "MIT",
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "spec",
+ "lib"
+ ],
+ "dependencies": {
+ "jquery": ">=1.8.3"
+ }
+}
diff --git a/demo/index.html b/demo/index.html
index 60d7e12..9788fc2 100644
--- a/demo/index.html
+++ b/demo/index.html
@@ -2,12 +2,12 @@
jQuery Mask Test
-
+
Date
99/99/9999
-
Phone
(999) 999-9999
+
Phone
(999) 999-9999
+
Phone(Readonly)
(999) 999-9999
Phone + Ext
(999) 999-9999? x99999
Int'l Phone
+33 999 999 999
Tax ID
99-9999999
@@ -38,6 +41,8 @@
Eye Script
~9.99 ~9.99 999
Purchase Order
aaa-999-***
Percent
99%
+
Phone (autoclear=false)
(999) 999-9999
+
Phone + Ext (autoclear=false)
(999) 999-9999? x99999
diff --git a/dist/jquery.maskedinput.js b/dist/jquery.maskedinput.js
index 49a5a72..4ac3cfc 100644
--- a/dist/jquery.maskedinput.js
+++ b/dist/jquery.maskedinput.js
@@ -1,338 +1,182 @@
/*
- Masked Input plugin for jQuery
- Copyright (c) 2007-2013 Josh Bush (digitalbush.com)
- Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
- Version: 1.3.1
+ jQuery Masked Input Plugin
+ Copyright (c) 2007 - 2015 Josh Bush (digitalbush.com)
+ Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
+ Version: 1.4.1
*/
-(function($) {
- function getPasteEvent() {
- var el = document.createElement('input'),
- name = 'onpaste';
- el.setAttribute(name, '');
- return (typeof el[name] === 'function')?'paste':'input';
-}
-
-var pasteEventName = getPasteEvent() + ".mask",
- ua = navigator.userAgent,
- iPhone = /iphone/i.test(ua),
- android=/android/i.test(ua),
- caretTimeoutId;
-
-$.mask = {
- //Predefined character definitions
- definitions: {
- '9': "[0-9]",
- 'a': "[A-Za-z]",
- '*': "[A-Za-z0-9]"
- },
- dataName: "rawMaskFn",
- placeholder: '_',
-};
-
-$.fn.extend({
- //Helper Function for Caret positioning
- caret: function(begin, end) {
- var range;
-
- if (this.length === 0 || this.is(":hidden")) {
- return;
- }
-
- if (typeof begin == 'number') {
- end = (typeof end === 'number') ? end : begin;
- return this.each(function() {
- if (this.setSelectionRange) {
- this.setSelectionRange(begin, end);
- } else if (this.createTextRange) {
- range = this.createTextRange();
- range.collapse(true);
- range.moveEnd('character', end);
- range.moveStart('character', begin);
- range.select();
- }
- });
- } else {
- if (this[0].setSelectionRange) {
- begin = this[0].selectionStart;
- end = this[0].selectionEnd;
- } else if (document.selection && document.selection.createRange) {
- range = document.selection.createRange();
- begin = 0 - range.duplicate().moveStart('character', -100000);
- end = begin + range.text.length;
- }
- return { begin: begin, end: end };
- }
- },
- unmask: function() {
- return this.trigger("unmask");
- },
- mask: function(mask, settings) {
- var input,
- defs,
- tests,
- partialPosition,
- firstNonMaskPos,
- len;
-
- if (!mask && this.length > 0) {
- input = $(this[0]);
- return input.data($.mask.dataName)();
- }
- settings = $.extend({
- placeholder: $.mask.placeholder, // Load default placeholder
- completed: null
- }, settings);
-
-
- defs = $.mask.definitions;
- tests = [];
- 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]));
- if (firstNonMaskPos === null) {
- firstNonMaskPos = tests.length - 1;
- }
- } else {
- tests.push(null);
- }
- });
-
- return this.trigger("unmask").each(function() {
- var input = $(this),
- buffer = $.map(
- mask.split(""),
- function(c, i) {
- if (c != '?') {
- return defs[c] ? settings.placeholder : c;
- }
- }),
- focusText = input.val();
-
- function seekNext(pos) {
- while (++pos < len && !tests[pos]);
- return pos;
- }
-
- function seekPrev(pos) {
- while (--pos >= 0 && !tests[pos]);
- return pos;
- }
-
- function shiftL(begin,end) {
- var i,
- j;
-
- if (begin<0) {
- return;
- }
-
- for (i = begin, j = seekNext(end); i < len; i++) {
- if (tests[i]) {
- if (j < len && tests[i].test(buffer[j])) {
- buffer[i] = buffer[j];
- buffer[j] = settings.placeholder;
- } else {
- break;
- }
-
- j = seekNext(j);
- }
- }
- writeBuffer();
- input.caret(Math.max(firstNonMaskPos, begin));
- }
-
- function shiftR(pos) {
- var i,
- c,
- j,
- t;
-
- for (i = pos, c = settings.placeholder; i < len; i++) {
- if (tests[i]) {
- j = seekNext(i);
- t = buffer[i];
- buffer[i] = c;
- if (j < len && tests[j].test(t)) {
- c = t;
- } else {
- break;
- }
- }
- }
- }
-
- function keydownEvent(e) {
- var k = e.which,
- pos,
- begin,
- end;
-
- //backspace, delete, and escape get special treatment
- if (k === 8 || k === 46 || (iPhone && k === 127)) {
- pos = input.caret();
- begin = pos.begin;
- end = pos.end;
-
- if (end - begin === 0) {
- begin=k!==46?seekPrev(begin):(end=seekNext(begin-1));
- end=k===46?seekNext(end):end;
- }
- clearBuffer(begin, end);
- shiftL(begin, end - 1);
-
- e.preventDefault();
- } else if (k == 27) {//escape
- input.val(focusText);
- input.caret(0, checkVal());
- e.preventDefault();
- }
- }
-
- function keypressEvent(e) {
- var k = e.which,
- pos = input.caret(),
- p,
- c,
- next;
-
- if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore
- return;
- } else if (k) {
- if (pos.end - pos.begin !== 0){
- clearBuffer(pos.begin, pos.end);
- shiftL(pos.begin, pos.end-1);
- }
-
- p = seekNext(pos.begin - 1);
- if (p < len) {
- c = String.fromCharCode(k);
- if (tests[p].test(c)) {
- shiftR(p);
-
- buffer[p] = c;
- writeBuffer();
- next = seekNext(p);
-
- if(android){
- setTimeout($.proxy($.fn.caret,input,next),0);
- }else{
- input.caret(next);
- }
-
- if (settings.completed && next >= len) {
- settings.completed.call(input);
- }
- }
- }
- e.preventDefault();
- }
- }
-
- function clearBuffer(start, end) {
- var i;
- for (i = start; i < end && i < len; i++) {
- if (tests[i]) {
- buffer[i] = settings.placeholder;
- }
- }
- }
-
- function writeBuffer() { input.val(buffer.join('')); }
-
- function checkVal(allow) {
- //try to place characters where they belong
- var test = input.val(),
- lastMatch = -1,
- i,
- c;
-
- 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)) {
- buffer[i] = c;
- lastMatch = i;
- break;
- }
- }
- if (pos > test.length) {
- break;
- }
- } else if (buffer[i] === test.charAt(pos) && i !== partialPosition) {
- pos++;
- lastMatch = i;
- }
- }
- if (allow) {
- writeBuffer();
- } else if (lastMatch + 1 < partialPosition) {
- input.val("");
- clearBuffer(0, len);
- } else {
- writeBuffer();
- input.val(input.val().substring(0, lastMatch + 1));
- }
- return (partialPosition ? i : firstNonMaskPos);
- }
-
- input.data($.mask.dataName,function(){
- return $.map(buffer, function(c, i) {
- return tests[i]&&c!=settings.placeholder ? c : null;
- }).join('');
- });
-
- if (!input.attr("readonly"))
- input
- .one("unmask", function() {
- input
- .unbind(".mask")
- .removeData($.mask.dataName);
- })
- .bind("focus.mask", function() {
- clearTimeout(caretTimeoutId);
- var pos,
- moveCaret;
-
- focusText = input.val();
- pos = checkVal();
-
- caretTimeoutId = setTimeout(function(){
- writeBuffer();
- if (pos == mask.length) {
- input.caret(0, pos);
- } else {
- input.caret(pos);
- }
- }, 10);
- })
- .bind("blur.mask", function() {
- checkVal();
- if (input.val() != focusText)
- input.change();
- })
- .bind("keydown.mask", keydownEvent)
- .bind("keypress.mask", keypressEvent)
- .bind(pasteEventName, function() {
- setTimeout(function() {
- var pos=checkVal(true);
- input.caret(pos);
- if (settings.completed && pos == input.val().length)
- settings.completed.call(input);
- }, 0);
- });
- checkVal(); //Perform initial check for existing values
- });
- }
-});
-
-
-})(jQuery);
\ No newline at end of file
+!function(factory) {
+ "function" == typeof define && define.amd ? define([ "jquery" ], factory) : factory("object" == typeof exports ? require("jquery") : jQuery);
+}(function($) {
+ var caretTimeoutId, ua = navigator.userAgent, iPhone = /iphone/i.test(ua), chrome = /chrome/i.test(ua), android = /android/i.test(ua);
+ $.mask = {
+ definitions: {
+ "9": "[0-9]",
+ a: "[A-Za-z]",
+ "*": "[A-Za-z0-9]"
+ },
+ autoclear: !0,
+ dataName: "rawMaskFn",
+ placeholder: "_"
+ }, $.fn.extend({
+ caret: function(begin, end) {
+ var range;
+ if (0 !== this.length && !this.is(":hidden")) return "number" == typeof begin ? (end = "number" == typeof end ? end : begin,
+ this.each(function() {
+ this.setSelectionRange ? this.setSelectionRange(begin, end) : this.createTextRange && (range = this.createTextRange(),
+ range.collapse(!0), range.moveEnd("character", end), range.moveStart("character", begin),
+ range.select());
+ })) : (this[0].setSelectionRange ? (begin = this[0].selectionStart, end = this[0].selectionEnd) : document.selection && document.selection.createRange && (range = document.selection.createRange(),
+ begin = 0 - range.duplicate().moveStart("character", -1e5), end = begin + range.text.length),
+ {
+ begin: begin,
+ end: end
+ });
+ },
+ unmask: function() {
+ return this.trigger("unmask");
+ },
+ mask: function(mask, settings) {
+ var input, defs, tests, partialPosition, firstNonMaskPos, lastRequiredNonMaskPos, len, oldVal;
+ if (!mask && this.length > 0) {
+ input = $(this[0]);
+ var fn = input.data($.mask.dataName);
+ return fn ? fn() : void 0;
+ }
+ return settings = $.extend({
+ autoclear: $.mask.autoclear,
+ placeholder: $.mask.placeholder,
+ completed: null
+ }, settings), defs = $.mask.definitions, tests = [], partialPosition = len = mask.length,
+ firstNonMaskPos = null, $.each(mask.split(""), function(i, c) {
+ "?" == c ? (len--, partialPosition = i) : defs[c] ? (tests.push(new RegExp(defs[c])),
+ null === firstNonMaskPos && (firstNonMaskPos = tests.length - 1), partialPosition > i && (lastRequiredNonMaskPos = tests.length - 1)) : tests.push(null);
+ }), this.trigger("unmask").each(function() {
+ function tryFireCompleted() {
+ if (settings.completed) {
+ for (var i = firstNonMaskPos; lastRequiredNonMaskPos >= i; i++) if (tests[i] && buffer[i] === getPlaceholder(i)) return;
+ settings.completed.call(input);
+ }
+ }
+ function getPlaceholder(i) {
+ return settings.placeholder.charAt(i < settings.placeholder.length ? i : 0);
+ }
+ function seekNext(pos) {
+ for (;++pos < len && !tests[pos]; ) ;
+ return pos;
+ }
+ function seekPrev(pos) {
+ for (;--pos >= 0 && !tests[pos]; ) ;
+ return pos;
+ }
+ function shiftL(begin, end) {
+ var i, j;
+ if (!(0 > begin)) {
+ for (i = begin, j = seekNext(end); len > i; i++) if (tests[i]) {
+ if (!(len > j && tests[i].test(buffer[j]))) break;
+ buffer[i] = buffer[j], buffer[j] = getPlaceholder(j), j = seekNext(j);
+ }
+ writeBuffer(), input.caret(Math.max(firstNonMaskPos, begin));
+ }
+ }
+ function shiftR(pos) {
+ var i, c, j, t;
+ for (i = pos, c = getPlaceholder(pos); len > i; i++) if (tests[i]) {
+ if (j = seekNext(i), t = buffer[i], buffer[i] = c, !(len > j && tests[j].test(t))) break;
+ c = t;
+ }
+ }
+ function androidInputEvent() {
+ var curVal = input.val(), pos = input.caret();
+ if (oldVal && oldVal.length && oldVal.length > curVal.length) {
+ for (checkVal(!0); pos.begin > 0 && !tests[pos.begin - 1]; ) pos.begin--;
+ if (0 === pos.begin) for (;pos.begin < firstNonMaskPos && !tests[pos.begin]; ) pos.begin++;
+ input.caret(pos.begin, pos.begin);
+ } else {
+ for (checkVal(!0); pos.begin < len && !tests[pos.begin]; ) pos.begin++;
+ input.caret(pos.begin, pos.begin);
+ }
+ tryFireCompleted();
+ }
+ function blurEvent() {
+ checkVal(), input.val() != focusText && input.change();
+ }
+ function keydownEvent(e) {
+ if (!input.prop("readonly")) {
+ var pos, begin, end, k = e.which || e.keyCode;
+ oldVal = input.val(), 8 === k || 46 === k || iPhone && 127 === k ? (pos = input.caret(),
+ begin = pos.begin, end = pos.end, end - begin === 0 && (begin = 46 !== k ? seekPrev(begin) : end = seekNext(begin - 1),
+ end = 46 === k ? seekNext(end) : end), clearBuffer(begin, end), shiftL(begin, end - 1),
+ e.preventDefault()) : 13 === k ? blurEvent.call(this, e) : 27 === k && (input.val(focusText),
+ input.caret(0, checkVal()), e.preventDefault());
+ }
+ }
+ function keypressEvent(e) {
+ if (!input.prop("readonly")) {
+ var p, c, next, k = e.which || e.keyCode, pos = input.caret();
+ if (!(e.ctrlKey || e.altKey || e.metaKey || 32 > k) && k && 13 !== k) {
+ if (pos.end - pos.begin !== 0 && (clearBuffer(pos.begin, pos.end), shiftL(pos.begin, pos.end - 1)),
+ p = seekNext(pos.begin - 1), len > p && (c = String.fromCharCode(k), tests[p].test(c))) {
+ if (shiftR(p), buffer[p] = c, writeBuffer(), next = seekNext(p), android) {
+ var proxy = function() {
+ $.proxy($.fn.caret, input, next)();
+ };
+ setTimeout(proxy, 0);
+ } else input.caret(next);
+ pos.begin <= lastRequiredNonMaskPos && tryFireCompleted();
+ }
+ e.preventDefault();
+ }
+ }
+ }
+ function clearBuffer(start, end) {
+ var i;
+ for (i = start; end > i && len > i; i++) tests[i] && (buffer[i] = getPlaceholder(i));
+ }
+ function writeBuffer() {
+ input.val(buffer.join(""));
+ }
+ function checkVal(allow) {
+ var i, c, pos, test = input.val(), lastMatch = -1;
+ for (i = 0, pos = 0; len > i; i++) if (tests[i]) {
+ for (buffer[i] = getPlaceholder(i); pos++ < test.length; ) if (c = test.charAt(pos - 1),
+ tests[i].test(c)) {
+ buffer[i] = c, lastMatch = i;
+ break;
+ }
+ if (pos > test.length) {
+ clearBuffer(i + 1, len);
+ break;
+ }
+ } else buffer[i] === test.charAt(pos) && pos++, partialPosition > i && (lastMatch = i);
+ return allow ? writeBuffer() : partialPosition > lastMatch + 1 ? settings.autoclear || buffer.join("") === defaultBuffer ? (input.val() && input.val(""),
+ clearBuffer(0, len)) : writeBuffer() : (writeBuffer(), input.val(input.val().substring(0, lastMatch + 1))),
+ partialPosition ? i : firstNonMaskPos;
+ }
+ var input = $(this), buffer = $.map(mask.split(""), function(c, i) {
+ return "?" != c ? defs[c] ? getPlaceholder(i) : c : void 0;
+ }), defaultBuffer = buffer.join(""), focusText = input.val();
+ input.data($.mask.dataName, function() {
+ return $.map(buffer, function(c, i) {
+ return tests[i] && c != getPlaceholder(i) ? c : null;
+ }).join("");
+ }), input.one("unmask", function() {
+ input.off(".mask").removeData($.mask.dataName);
+ }).on("focus.mask", function() {
+ if (!input.prop("readonly")) {
+ clearTimeout(caretTimeoutId);
+ var pos;
+ focusText = input.val(), pos = checkVal(), caretTimeoutId = setTimeout(function() {
+ input.get(0) === document.activeElement && (writeBuffer(), pos == mask.replace("?", "").length ? input.caret(0, pos) : input.caret(pos));
+ }, 10);
+ }
+ }).on("blur.mask", blurEvent).on("keydown.mask", keydownEvent).on("keypress.mask", keypressEvent).on("input.mask paste.mask", function() {
+ input.prop("readonly") || setTimeout(function() {
+ var pos = checkVal(!0);
+ input.caret(pos), tryFireCompleted();
+ }, 0);
+ }), chrome && android && input.off("input.mask").on("input.mask", androidInputEvent),
+ checkVal();
+ });
+ }
+ });
+});
\ No newline at end of file
diff --git a/dist/jquery.maskedinput.min.js b/dist/jquery.maskedinput.min.js
index 0d9ce6e..d4dfd01 100644
--- a/dist/jquery.maskedinput.min.js
+++ b/dist/jquery.maskedinput.min.js
@@ -1,7 +1,7 @@
/*
- Masked Input plugin for jQuery
- Copyright (c) 2007-2013 Josh Bush (digitalbush.com)
- Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
- Version: 1.3.1
+ jQuery Masked Input Plugin
+ Copyright (c) 2007 - 2015 Josh Bush (digitalbush.com)
+ Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
+ Version: 1.4.1
*/
-(function(e){function t(){var e=document.createElement("input"),t="onpaste";return e.setAttribute(t,""),"function"==typeof e[t]?"paste":"input"}var n,a=t()+".mask",r=navigator.userAgent,i=/iphone/i.test(r),o=/android/i.test(r);e.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn",placeholder:"_"},e.fn.extend({caret:function(e,t){var n;if(0!==this.length&&!this.is(":hidden"))return"number"==typeof e?(t="number"==typeof t?t:e,this.each(function(){this.setSelectionRange?this.setSelectionRange(e,t):this.createTextRange&&(n=this.createTextRange(),n.collapse(!0),n.moveEnd("character",t),n.moveStart("character",e),n.select())})):(this[0].setSelectionRange?(e=this[0].selectionStart,t=this[0].selectionEnd):document.selection&&document.selection.createRange&&(n=document.selection.createRange(),e=0-n.duplicate().moveStart("character",-1e5),t=e+n.text.length),{begin:e,end:t})},unmask:function(){return this.trigger("unmask")},mask:function(t,r){var c,l,s,u,f,h;return!t&&this.length>0?(c=e(this[0]),c.data(e.mask.dataName)()):(r=e.extend({placeholder:e.mask.placeholder,completed:null},r),l=e.mask.definitions,s=[],u=h=t.length,f=null,e.each(t.split(""),function(e,t){"?"==t?(h--,u=e):l[t]?(s.push(RegExp(l[t])),null===f&&(f=s.length-1)):s.push(null)}),this.trigger("unmask").each(function(){function c(e){for(;h>++e&&!s[e];);return e}function d(e){for(;--e>=0&&!s[e];);return e}function m(e,t){var n,a;if(!(0>e)){for(n=e,a=c(t);h>n;n++)if(s[n]){if(!(h>a&&s[n].test(R[a])))break;R[n]=R[a],R[a]=r.placeholder,a=c(a)}b(),x.caret(Math.max(f,e))}}function p(e){var t,n,a,i;for(t=e,n=r.placeholder;h>t;t++)if(s[t]){if(a=c(t),i=R[t],R[t]=n,!(h>a&&s[a].test(i)))break;n=i}}function g(e){var t,n,a,r=e.which;8===r||46===r||i&&127===r?(t=x.caret(),n=t.begin,a=t.end,0===a-n&&(n=46!==r?d(n):a=c(n-1),a=46===r?c(a):a),k(n,a),m(n,a-1),e.preventDefault()):27==r&&(x.val(S),x.caret(0,y()),e.preventDefault())}function v(t){var n,a,i,l=t.which,u=x.caret();t.ctrlKey||t.altKey||t.metaKey||32>l||l&&(0!==u.end-u.begin&&(k(u.begin,u.end),m(u.begin,u.end-1)),n=c(u.begin-1),h>n&&(a=String.fromCharCode(l),s[n].test(a)&&(p(n),R[n]=a,b(),i=c(n),o?setTimeout(e.proxy(e.fn.caret,x,i),0):x.caret(i),r.completed&&i>=h&&r.completed.call(x))),t.preventDefault())}function k(e,t){var n;for(n=e;t>n&&h>n;n++)s[n]&&(R[n]=r.placeholder)}function b(){x.val(R.join(""))}function y(e){var t,n,a=x.val(),i=-1;for(t=0,pos=0;h>t;t++)if(s[t]){for(R[t]=r.placeholder;pos++a.length)break}else R[t]===a.charAt(pos)&&t!==u&&(pos++,i=t);return e?b():u>i+1?(x.val(""),k(0,h)):(b(),x.val(x.val().substring(0,i+1))),u?t:f}var x=e(this),R=e.map(t.split(""),function(e){return"?"!=e?l[e]?r.placeholder:e:void 0}),S=x.val();x.data(e.mask.dataName,function(){return e.map(R,function(e,t){return s[t]&&e!=r.placeholder?e:null}).join("")}),x.attr("readonly")||x.one("unmask",function(){x.unbind(".mask").removeData(e.mask.dataName)}).bind("focus.mask",function(){clearTimeout(n);var e;S=x.val(),e=y(),n=setTimeout(function(){b(),e==t.length?x.caret(0,e):x.caret(e)},10)}).bind("blur.mask",function(){y(),x.val()!=S&&x.change()}).bind("keydown.mask",g).bind("keypress.mask",v).bind(a,function(){setTimeout(function(){var e=y(!0);x.caret(e),r.completed&&e==x.val().length&&r.completed.call(x)},0)}),y()}))}})})(jQuery);
\ No newline at end of file
+!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a){var b,c=navigator.userAgent,d=/iphone/i.test(c),e=/chrome/i.test(c),f=/android/i.test(c);a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},autoclear:!0,dataName:"rawMaskFn",placeholder:"_"},a.fn.extend({caret:function(a,b){var c;if(0!==this.length&&!this.is(":hidden"))return"number"==typeof a?(b="number"==typeof b?b:a,this.each(function(){this.setSelectionRange?this.setSelectionRange(a,b):this.createTextRange&&(c=this.createTextRange(),c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select())})):(this[0].setSelectionRange?(a=this[0].selectionStart,b=this[0].selectionEnd):document.selection&&document.selection.createRange&&(c=document.selection.createRange(),a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length),{begin:a,end:b})},unmask:function(){return this.trigger("unmask")},mask:function(c,g){var h,i,j,k,l,m,n,o;if(!c&&this.length>0){h=a(this[0]);var p=h.data(a.mask.dataName);return p?p():void 0}return g=a.extend({autoclear:a.mask.autoclear,placeholder:a.mask.placeholder,completed:null},g),i=a.mask.definitions,j=[],k=n=c.length,l=null,a.each(c.split(""),function(a,b){"?"==b?(n--,k=a):i[b]?(j.push(new RegExp(i[b])),null===l&&(l=j.length-1),k>a&&(m=j.length-1)):j.push(null)}),this.trigger("unmask").each(function(){function h(){if(g.completed){for(var a=l;m>=a;a++)if(j[a]&&C[a]===p(a))return;g.completed.call(B)}}function p(a){return g.placeholder.charAt(a=0&&!j[a];);return a}function s(a,b){var c,d;if(!(0>a)){for(c=a,d=q(b);n>c;c++)if(j[c]){if(!(n>d&&j[c].test(C[d])))break;C[c]=C[d],C[d]=p(d),d=q(d)}z(),B.caret(Math.max(l,a))}}function t(a){var b,c,d,e;for(b=a,c=p(a);n>b;b++)if(j[b]){if(d=q(b),e=C[b],C[b]=c,!(n>d&&j[d].test(e)))break;c=e}}function u(){var a=B.val(),b=B.caret();if(o&&o.length&&o.length>a.length){for(A(!0);b.begin>0&&!j[b.begin-1];)b.begin--;if(0===b.begin)for(;b.beging)&&g&&13!==g){if(i.end-i.begin!==0&&(y(i.begin,i.end),s(i.begin,i.end-1)),c=q(i.begin-1),n>c&&(d=String.fromCharCode(g),j[c].test(d))){if(t(c),C[c]=d,z(),e=q(c),f){var k=function(){a.proxy(a.fn.caret,B,e)()};setTimeout(k,0)}else B.caret(e);i.begin<=m&&h()}b.preventDefault()}}}function y(a,b){var c;for(c=a;b>c&&n>c;c++)j[c]&&(C[c]=p(c))}function z(){B.val(C.join(""))}function A(a){var b,c,d,e=B.val(),f=-1;for(b=0,d=0;n>b;b++)if(j[b]){for(C[b]=p(b);d++e.length){y(b+1,n);break}}else C[b]===e.charAt(d)&&d++,k>b&&(f=b);return a?z():k>f+1?g.autoclear||C.join("")===D?(B.val()&&B.val(""),y(0,n)):z():(z(),B.val(B.val().substring(0,f+1))),k?b:l}var B=a(this),C=a.map(c.split(""),function(a,b){return"?"!=a?i[a]?p(b):a:void 0}),D=C.join(""),E=B.val();B.data(a.mask.dataName,function(){return a.map(C,function(a,b){return j[b]&&a!=p(b)?a:null}).join("")}),B.one("unmask",function(){B.off(".mask").removeData(a.mask.dataName)}).on("focus.mask",function(){if(!B.prop("readonly")){clearTimeout(b);var a;E=B.val(),a=A(),b=setTimeout(function(){B.get(0)===document.activeElement&&(z(),a==c.replace("?","").length?B.caret(0,a):B.caret(a))},10)}}).on("blur.mask",v).on("keydown.mask",w).on("keypress.mask",x).on("input.mask paste.mask",function(){B.prop("readonly")||setTimeout(function(){var a=A(!0);B.caret(a),h()},0)}),e&&f&&B.off("input.mask").on("input.mask",u),A()})}})});
\ No newline at end of file
diff --git a/gruntfile.js b/gruntfile.js
new file mode 100644
index 0000000..5b22eac
--- /dev/null
+++ b/gruntfile.js
@@ -0,0 +1,62 @@
+
+"use strict";
+
+module.exports = function( grunt ) {
+ grunt.initConfig({
+ // TODO: change to read component.json
+ pkg: require('./package.json'),
+
+ uglify: {
+ options: {
+ banner: '/*\n <%= pkg.description %>\n Copyright (c) 2007 - <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)\n Version: <%= pkg.version %>\n*/\n'
+ },
+
+ dev: {
+ options: {
+ beautify: true,
+ mangle: false
+ },
+
+ files: {
+ 'dist/jquery.maskedinput.js': ['src/jquery.maskedinput.js']
+ }
+ },
+
+ min: {
+ files: {
+ 'dist/jquery.maskedinput.min.js': ['src/jquery.maskedinput.js']
+ }
+ }
+ },
+
+ jasmine: {
+ full: {
+ src: "src/**/*.js",
+ options: {
+ specs: "spec/*[S|s]pec.js",
+ vendor: [
+ "spec/lib/matchers.js",
+ "spec/lib/jasmine-species/jasmine-grammar.js",
+ "spec/lib/setup.js",
+ "lib/jquery-1.9.0.min.js",
+ "spec/lib/jquery.keymasher.js"
+ ]
+ }
+ }
+ },
+ nugetpack: {
+ dist: {
+ src: 'jquery.maskedinput.nuspec',
+ dest: 'dist/'
+ }
+ }
+ });
+
+ grunt.loadNpmTasks("grunt-contrib-jasmine");
+ grunt.loadNpmTasks("grunt-contrib-uglify");
+ grunt.loadNpmTasks('grunt-nuget');
+
+ grunt.registerTask('test', ['jasmine']);
+ grunt.registerTask('pack', ['default','nugetpack']);
+ grunt.registerTask('default', ['test', 'uglify']);
+};
diff --git a/jquery.maskedinput.nuspec b/jquery.maskedinput.nuspec
new file mode 100644
index 0000000..9e88140
--- /dev/null
+++ b/jquery.maskedinput.nuspec
@@ -0,0 +1,21 @@
+
+
+
+ jQuery.MaskedInput
+ 1.4.1.0
+ digitalBush
+ stimms
+ https://github.com/digitalBush/jquery.maskedinput/blob/master/LICENSE
+ http://digitalbush.com/projects/masked-input-plugin/
+ false
+ A jQuery plugin which applies a mask to input boxes to provide both a UI hint for users as well as some rudimentary input checking.
+ jQuery,plugins
+
+
+
+
+
+
+
+
+
diff --git a/maskedinput.jquery.json b/maskedinput.jquery.json
deleted file mode 100644
index c44ab46..0000000
--- a/maskedinput.jquery.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "name": "maskedinput",
- "title": "jQuery Masked Input",
- "description": "jQuery plugin for forcing fixed width inputs to follow a certain patern.",
- "keywords": ["input", "form", "mask"],
- "version": "1.3.1",
- "author": {
- "name": "Josh Bush",
- "url": "http://digitalbush.com"
- },
- "licenses": [
- {
- "type": "MIT",
- "url": "https://raw.github.com/digitalBush/jquery.maskedinput/master/LICENSE"
- }
- ],
- "bugs": "https://github.com/digitalBush/jquery.maskedinput/issues",
- "homepage": "http://digitalbush.com/projects/masked-input-plugin/",
- "docs": "http://digitalbush.com/projects/masked-input-plugin/#usage",
- "dependencies": {
- "jquery": ">=1.5"
- }
-}
\ No newline at end of file
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..8c65c9b
--- /dev/null
+++ b/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "jquery.maskedinput",
+ "version": "1.4.1",
+ "author": "Josh Bush (digitalbush.com)",
+ "description": "jQuery Masked Input Plugin",
+ "devDependencies": {
+ "grunt": "0.4.x",
+ "grunt-contrib-jasmine": "0.5.x",
+ "grunt-contrib-uglify": "0.2.x",
+ "grunt-contrib-watch": "0.5.x",
+ "grunt-nuget": "^0.1.4"
+ },
+ "scripts": {
+ "test": "grunt test"
+ }
+}
diff --git a/plugin.json b/plugin.json
deleted file mode 100644
index e2aa63d..0000000
--- a/plugin.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "name" : "jquery.maskedinput",
- "author" : "Josh Bush (digitalbush.com)",
- "version" : "1.3.1"
-}
diff --git a/spec/Completed.Spec.js b/spec/Completed.Spec.js
new file mode 100644
index 0000000..be71e62
--- /dev/null
+++ b/spec/Completed.Spec.js
@@ -0,0 +1,122 @@
+feature("Completed callback", function() {
+ scenario('Completing mask by typing last character',function(){
+ var completed=false;
+ given("an input with a completed callback", function(){
+ input.mask("99",{completed:function(){completed=true;}});
+ });
+
+ when("typing left to right",function(){
+ input.mashKeys("12");
+ });
+
+ then("completed callback should be called",function(){
+ expect(completed).toBeTruthy();
+ });
+ then("value should be correct",function(){
+ expect(input).toHaveValue('12');
+ });
+ });
+
+ scenario('Completing mask by typing first character',function(){
+ var completed=false;
+ given("an input with a completed callback", function(){
+ input.val("12").mask("99",{completed:function(){completed=true;}});
+ });
+
+ when("replacing first character value",function(){
+ input
+ .caret(1)
+ .mashKeys(function(keys){keys.type(keys.backspace)})
+ .mashKeys("3");
+ });
+
+ then("completed callback should be called",function(){
+ expect(completed).toBeTruthy();
+ });
+
+ then("value should be correct",function(){
+ expect(input).toHaveValue('32');
+ });
+ });
+
+ scenario('Typing last character of incomplete mask',function(){
+ var completed=false;
+ given("an input with a completed callback", function(){
+ input
+ .mask("99",{completed:function(){completed=true;}})
+ .mashKeys("1")
+ .mashKeys(function(keys){keys.type(keys.backspace)});
+ });
+
+ when("moving cursor to last position and typing",function(){
+ input.caret(1).mashKeys("5");
+ });
+
+ then("completed callback should not be called",function(){
+ expect(completed).toBeFalsy();
+ });
+
+ then("value should be correct",function(){
+ expect(input).toHaveValue('_5');
+ });
+
+ });
+
+ scenario('Typing last character of required portion of mask containing optional',function(){
+ var completed=false;
+ given("an input with a completed callback", function(){
+ input.mask("99?99",{completed:function(){completed=true;}});
+ });
+
+ when("typing left to right",function(){
+ input.mashKeys("12");
+ });
+
+ then("completed callback should be called",function(){
+ expect(completed).toBeTruthy();
+ });
+
+ then("value should be correct",function(){
+ expect(input).toHaveValue('12__');
+ });
+ });
+
+ scenario('Typing all characters of required portion of mask containing optional',function(){
+ var completedCount=0;
+ given("an input with a completed callback", function(){
+ input.mask("99?99",{completed:function(){completedCount++;}});
+ });
+
+ when("typing left to right",function(){
+ input.mashKeys("1234");
+ });
+
+ then("completed callback should be called",function(){
+ expect(completedCount).toEqual(1);
+ });
+
+ then("value should be correct",function(){
+ expect(input).toHaveValue('1234');
+ });
+ });
+
+ scenario('Completing mask by typing last character with literal to right',function(){
+ var completed=false;
+ given("an input with a completed callback", function(){
+ input.mask("99!",{completed:function(){completed=true;}});
+ });
+
+ when("typing left to right",function(){
+ input.mashKeys("12");
+ });
+
+ then("completed callback should be called",function(){
+ expect(completed).toBeTruthy();
+ });
+ then("value should be correct",function(){
+ expect(input).toHaveValue('12!');
+ });
+ });
+
+
+});
diff --git a/spec/Enter.Spec.js b/spec/Enter.Spec.js
new file mode 100644
index 0000000..025e21e
--- /dev/null
+++ b/spec/Enter.Spec.js
@@ -0,0 +1,118 @@
+feature("Enter Key", function() {
+ var enterKeyEvent = $.Event('keydown.mask');
+ enterKeyEvent.which = enterKeyEvent.keyCode = 13;
+
+ story('User presses enter key after typing in some changes',function(){
+ scenario("All placeholders filled",function(){
+ given("a mask with two placeholders",function(){
+ input.mask("99");
+ });
+ when("typing two characters and pressing enter",function(){
+ input.mashKeys("12").trigger(enterKeyEvent);
+ });
+ then("value should be correct",function(){
+ expect(input).toHaveValue("12");
+ });
+ });
+
+ scenario("Empty placeholders remaining",function(){
+ given("a mask with two placeholders",function(){
+ input.mask("99");
+ });
+ when("typing one character and pressing enter",function(){
+ input.mashKeys("1").trigger(enterKeyEvent);
+ });
+ then("value should be empty",function(){
+ expect(input).toHaveValue("");
+ });
+ });
+
+ scenario("Empty placeholders remaining with autoclear set to false",function(){
+ given("a mask with two placeholders",function(){
+ input.mask("99", { autoclear: false });
+ });
+ when("typing one character and pressing enter",function(){
+ input.caret(0);
+ input.mashKeys("1")
+ input.trigger(enterKeyEvent);
+ });
+ then("value should remain visible with placeholders",function(){
+ expect(input).toHaveValue("1_");
+ });
+ });
+ });
+
+ story("User presses enter key after typing in some changes and masks contain Optional Markers",function(){
+ scenario("Placeholders not filled to marker",function(){
+ given("a mask with an optional marker",function(){
+ input.mask("99?99");
+ });
+ when("typing one character and leaving",function(){
+ input.mashKeys("1").trigger(enterKeyEvent);
+ });
+ then("value should be empty",function(){
+ expect(input).toHaveValue("");
+ });
+ });
+
+ scenario("Placeholders not filled to marker and autoclear = false", function() {
+ given("a mask with an optional marker",function(){
+ input.mask("99?99", { autoclear: false });
+ });
+ when("typing one character and leaving",function(){
+ input.mashKeys("1").trigger(enterKeyEvent);
+ });
+ then("value should be empty",function(){
+ expect(input).toHaveValue("1___");
+ });
+ });
+
+ scenario("Placeholders filled to marker",function(){
+ given("a mask with an optional marker",function(){
+ input.mask("99?99");
+ });
+ when("typing two characters and leaving",function(){
+ input.mashKeys("12").trigger(enterKeyEvent);
+ });
+ then("value should remain",function(){
+ expect(input).toHaveValue("12");
+ });
+ });
+
+ scenario("Placeholders filled to marker and autoclear = false", function() {
+ given("a mask with an optional marker",function(){
+ input.mask("99?99", { autoclear: false });
+ });
+ when("typing two characters and leaving",function(){
+ input.mashKeys("12").trigger(enterKeyEvent);
+ });
+ then("value should remain",function(){
+ expect(input).toHaveValue("12");
+ });
+ });
+
+ scenario("Placeholders filled, one marker filled, and autoclear = false", function() {
+ given("a mask with an optional marker",function(){
+ input.mask("99?99", { autoclear: false });
+ });
+ when("typing three characters and leaving",function(){
+ input.mashKeys("123").trigger(enterKeyEvent);
+ });
+ then("value should remain",function(){
+ expect(input).toHaveValue("123");
+ });
+ });
+
+ scenario("Placeholders and markers filled, and autoclear = false", function() {
+ given("a mask with an optional marker",function(){
+ input.mask("99?99", { autoclear: false });
+ });
+ when("typing four characters and leaving",function(){
+ input.mashKeys("1234").trigger(enterKeyEvent);
+ });
+ then("value should remain",function(){
+ expect(input).toHaveValue("1234");
+ });
+ });
+ });
+});
diff --git a/spec/Focus.Spec.js b/spec/Focus.Spec.js
index b7a2143..4e5743e 100644
--- a/spec/Focus.Spec.js
+++ b/spec/Focus.Spec.js
@@ -35,6 +35,34 @@ feature("Focusing A Masked Input",function(){
});
});
+ scenario("Mask starts with a literal that fits first placeholder",function(){
+ given("a mask beginning with a literal",function(){
+ input.mask("19").focus();
+ });
+ waits(20);
+ when("blurring",function(){
+ input.blur();
+ });
+ waits(20);
+ then("input value should be correct",function(){
+ expect(input).toHaveValue('');
+ });
+ });
+
+ scenario("Mask starts with a literal that fits first placeholder and autoclear set to false",function(){
+ given("a mask beginning with a literal",function(){
+ input.mask("?19",{autoclear: false}).focus();
+ });
+ waits(20);
+ when("blurring",function(){
+ input.blur();
+ });
+ waits(20);
+ then("input value should be correct",function(){
+ expect(input).toHaveValue('');
+ });
+ });
+
scenario("Masking a hidden input",function(){
var error;
$(window).on("error.test",function(err){error=err;})
@@ -50,6 +78,42 @@ feature("Focusing A Masked Input",function(){
expect(error).toBeUndefined();
})
});
+
+ scenario("Mask contains a partial value with autoclear set to false",function(){
+ given("the input has a partial value",function(){
+ input.val("1");
+ });
+ given("a mask with two placeholders and autoclear=false",function(){
+ input.mask("99", { autoclear: false });
+ });
+ when("focusing on the input",function(){
+ input.focus();
+ });
+ then("the value should be partially filled out",function(){
+ expect(input).toHaveValue("1_");
+ });
+ then("the input partial value should remain",function(){
+ expect(input).toHaveValue("1_");
+ });
+ });
+
+ scenario("Mask containing optional mask ?",function(){
+ given("the input has a partial value",function(){
+ input.val("99");
+ });
+ given("a optional mask on input",function(){
+ input.mask("9?9");
+ });
+ when("focusing input",function(){
+ input.focus();
+ });
+ waits(1);
+ then("caret position should be correct",function(){
+ var caret=input.caret();
+ expect(caret.begin).toEqual(0);
+ expect(caret.end).toEqual(2);
+ });
+ });
});
feature("Leaving A Masked Input",function(){
@@ -76,30 +140,47 @@ feature("Leaving A Masked Input",function(){
expect(input).toHaveValue("");
});
});
-});
-feature("Optional marker",function(){
- scenario("Placeholders not filled to marker",function(){
- given("a mask with an optional marker",function(){
- input.mask("99?99");
+ scenario("Mask ending in literal",function(){
+ given("a mask ending in a literal",function(){
+ input.mask("99!");
});
- when("typing one character and leaving",function(){
- input.mashKeys("1").blur();
+ when("typing two characters and blurring",function(){
+ input.mashKeys("12").blur();
});
- then("value should be empty",function(){
- expect(input).toHaveValue("");
+ then("value should remain",function(){
+ expect(input).toHaveValue("12!");
});
});
- scenario("Placeholders filled to marker",function(){
- given("a mask with an optional marker",function(){
- input.mask("99?99");
+ scenario("Empty placeholders remaining with autoclear set to false",function(){
+ given("a mask with two placeholders",function(){
+ input.mask("99", { autoclear: false });
});
- when("typing two characters and leaving",function(){
- input.mashKeys("12").blur();
+ when("typing one character and blurring",function(){
+ input.caret(0);
+ input.mashKeys("1")
+ input.blur();
});
- then("value should remain",function(){
- expect(input).toHaveValue("12");
+ then("value should remain visible with placeholders",function(){
+ expect(input).toHaveValue("1_");
+ });
+ });
+
+ scenario("Shifts characters left on blur with autoclear false",function(){
+ given("a mask with 10 placeholders",function(){
+ input.mask("(999) 999-9999", { autoclear: false });
+ });
+ when("focusing input",function(){
+ input.focus();
+ });
+ waits(20);
+ when("typing characters at the end of the mask and blurring",function(){
+ input.caret(12);
+ input.mashKeys("44").blur();
+ });
+ then("characters should shift left to beginning of mask",function(){
+ expect(input).toHaveValue("(44_) ___-____");
});
});
});
diff --git a/spec/Init.Spec.js b/spec/Init.Spec.js
new file mode 100644
index 0000000..e53cfe8
--- /dev/null
+++ b/spec/Init.Spec.js
@@ -0,0 +1,73 @@
+feature("Initializing a Mask",function(){
+ scenario("An input with no value",function(){
+ given("an input with no value",function(){
+ input.val("");
+ });
+ when("setting a mask with two placeholders",function(){
+ input.mask("99");
+ });
+ then("the value should be an empty string",function(){
+ expect(input).toHaveValue("");
+ });
+ });
+
+ scenario("An input with a valid value and no placeholders remaining",function(){
+ given("an input with a valid value",function(){
+ input.val("5555555555");
+ });
+ when("setting a mask",function(){
+ input.mask("(999) 999-9999");
+ });
+ then("the value should be intact",function(){
+ expect(input).toHaveValue("(555) 555-5555");
+ });
+ });
+
+ scenario("An input with a valid value ending in a literal",function(){
+ given("an input with a valid value",function(){
+ input.val("12");
+ });
+ when("setting a mask",function(){
+ input.mask("(99)");
+ });
+ then("the value should be intact",function(){
+ expect(input).toHaveValue("(12)");
+ });
+ });
+
+ scenario("An input with an invalid value and placeholders remaining",function(){
+ given("an invalid input value",function(){
+ input.val("55555555");
+ });
+ when("setting a mask",function(){
+ input.mask("(999) 999-9999");
+ });
+ then("the value should be empty",function(){
+ expect(input).toHaveValue("");
+ });
+ });
+
+ scenario("An input with an invalid value, placeholders remaining and autoclear set to false",function(){
+ given("an invalid input value",function(){
+ input.val("55555555");
+ });
+ when("setting a mask with autoclear set to false",function(){
+ input.mask("(999) 999-9999", { autoclear: false });
+ });
+ then("the value be intact with placeholders visible",function(){
+ expect(input).toHaveValue("(555) 555-55__");
+ });
+ });
+
+ scenario("An input no value and autoclear set to false", function() {
+ given("an input with no value",function(){
+ input.val("");
+ });
+ when("setting a mask with autoclear set to false",function(){
+ input.mask("(999) 999-9999", { autoclear: false });
+ });
+ then("the value should be empty",function(){
+ expect(input).toHaveValue("");
+ });
+ });
+});
diff --git a/spec/Optional.Spec.js b/spec/Optional.Spec.js
new file mode 100644
index 0000000..83e14ae
--- /dev/null
+++ b/spec/Optional.Spec.js
@@ -0,0 +1,85 @@
+feature("Optional marker",function(){
+ scenario("Placeholders not filled to marker",function(){
+ given("a mask with an optional marker",function(){
+ input.mask("99?99");
+ });
+ when("typing one character and leaving",function(){
+ input.mashKeys("1").blur();
+ });
+ then("value should be empty",function(){
+ expect(input).toHaveValue("");
+ });
+ });
+
+ scenario("Placeholders not filled to marker and autoclear = false", function() {
+ given("a mask with an optional marker",function(){
+ input.mask("99?99", { autoclear: false });
+ });
+ when("typing one character and leaving",function(){
+ input.mashKeys("1").blur();
+ });
+ then("value should be empty",function(){
+ expect(input).toHaveValue("1___");
+ });
+ });
+
+ scenario("Placeholders filled to marker",function(){
+ given("a mask with an optional marker",function(){
+ input.mask("99?99");
+ });
+ when("typing two characters and leaving",function(){
+ input.mashKeys("12").blur();
+ });
+ then("value should remain",function(){
+ expect(input).toHaveValue("12");
+ });
+ });
+
+ scenario("Placeholders filled to marker with literals after",function(){
+ given("a mask with an optional marker and literals",function(){
+ input.mask("99!? x 99");
+ });
+ when("typing two characters and leaving",function(){
+ input.mashKeys("12").blur();
+ });
+ then("value should remain",function(){
+ expect(input).toHaveValue("12!");
+ });
+ });
+
+ scenario("Placeholders filled to marker and autoclear = false", function() {
+ given("a mask with an optional marker",function(){
+ input.mask("99?99", { autoclear: false });
+ });
+ when("typing two characters and leaving",function(){
+ input.mashKeys("12").blur();
+ });
+ then("value should remain",function(){
+ expect(input).toHaveValue("12");
+ });
+ });
+
+ scenario("Placeholders filled, one marker filled, and autoclear = false", function() {
+ given("a mask with an optional marker",function(){
+ input.mask("99?99", { autoclear: false });
+ });
+ when("typing three characters and leaving",function(){
+ input.mashKeys("123").blur();
+ });
+ then("value should remain",function(){
+ expect(input).toHaveValue("123");
+ });
+ });
+
+ scenario("Placeholders and markers filled, and autoclear = false", function() {
+ given("a mask with an optional marker",function(){
+ input.mask("99?99", { autoclear: false });
+ });
+ when("typing four characters and leaving",function(){
+ input.mashKeys("1234").blur();
+ });
+ then("value should remain",function(){
+ expect(input).toHaveValue("1234");
+ });
+ });
+});
diff --git a/spec/Placeholder.spec.js b/spec/Placeholder.spec.js
new file mode 100644
index 0000000..8bf5f0f
--- /dev/null
+++ b/spec/Placeholder.spec.js
@@ -0,0 +1,27 @@
+feature("Multiple character placeholders",function(){
+ scenario("Focusing",function(){
+ given("a mask beginning with multi character placeholder",function(){
+ input.mask("99/9999",{placeholder:"mm/yyyy"});
+ });
+ when("focusing",function(){
+ input.focus();
+ });
+ waits(20);
+ then("placeholder text should be correct",function(){
+ expect(input).toHaveValue('mm/yyyy');
+ });
+ });
+
+ scenario("Typing",function(){
+ given("a mask beginning with multi character placeholder",function(){
+ input.mask("99/9999",{placeholder:"mm/yyyy"});
+ });
+ when("typing",function(){
+ input.mashKeys("12");
+ });
+ waits(20);
+ then("placeholder text should be correct",function(){
+ expect(input).toHaveValue('12/yyyy');
+ });
+ });
+});
diff --git a/spec/Raw.Spec.js b/spec/Raw.Spec.js
index 0516971..52a3ed7 100644
--- a/spec/Raw.Spec.js
+++ b/spec/Raw.Spec.js
@@ -54,4 +54,97 @@ feature("Getting raw value",function(){
expect(input.mask()).toEqual("12");
});
});
-});
\ No newline at end of file
+
+ scenario("Verify if the input hasn't the mask bound through the raw value", function() {
+ given("an input without a mask", function() {
+ input
+ .mask("9/9-9_9").unmask();
+ });
+
+ then("The raw value should be undefined and no error must occur", function() {
+ expect(input.mask()).toBe(undefined);
+ });
+ });
+});
+
+feature("Getting raw value with autoclear set to false", function() {
+ scenario("After typing",function(){
+ given("an input with a mask containing a literal", function(){
+ input.mask("9/9", { autoclear: false });
+ });
+
+ when("typing all numbers",function(){
+ input.mashKeys("12");
+ });
+
+ then("raw value should be correct",function(){
+ expect(input.mask()).toEqual("12");
+ });
+ });
+
+ scenario("While typing",function(){
+ given("an input with a mask containing a literal", function(){
+ input.mask("9/9", { autoclear: false });
+ });
+
+ when("typing a number",function(){
+ input.mashKeys("1");
+ });
+
+ then("raw value should be correct",function(){
+ expect(input.mask()).toEqual("1");
+ });
+ });
+
+ scenario("Before typing",function(){
+ given("an input with a mask containing a literal", function(){
+ input.mask("9/9", { autoclear: false });
+ });
+
+ then("raw value should be correct",function(){
+ expect(input.mask()).toEqual("");
+ });
+ });
+
+ scenario("After typing partial input past an optional marker",function(){
+ given("an input with a mask containing a literal", function(){
+ input.mask("9?99", { autoclear: false });
+ });
+
+ when("typing a partial input",function(){
+ input.mashKeys("12");
+ });
+
+ then("raw value should be correct",function(){
+ expect(input.mask()).toEqual("12");
+ });
+ });
+
+ scenario("After typing partial input",function(){
+ given("an input with a mask containing a literal", function(){
+ input.mask("99?99", { autoclear: false });
+ });
+
+ when("typing a partial input",function(){
+ input.mashKeys("1");
+ });
+
+ then("raw value should be correct",function(){
+ expect(input.mask()).toEqual("1");
+ });
+ });
+
+ scenario("After typing partial input up to an optional marker",function(){
+ given("an input with a mask containing a literal", function(){
+ input.mask("9?99", { autoclear: false });
+ });
+
+ when("typing a partial input",function(){
+ input.mashKeys("1");
+ });
+
+ then("raw value should be correct",function(){
+ expect(input.mask()).toEqual("1");
+ });
+ });
+});
diff --git a/spec/Readonly.Spec.js b/spec/Readonly.Spec.js
new file mode 100644
index 0000000..6f37d1f
--- /dev/null
+++ b/spec/Readonly.Spec.js
@@ -0,0 +1,16 @@
+feature("Readonly Inputs", function() {
+ scenario('Typing',function(){
+
+ given("a input with readonly added after mask", function(){
+ input.mask("99").attr("readonly",true);
+ });
+
+ when("typing left to right",function(){
+ input.mashKeys("12");
+ });
+
+ then("Input should be ignored",function(){
+ expect(input).toHaveValue("");
+ });
+ });
+});
diff --git a/spec/SpecRunner.html b/spec/SpecRunner.html
deleted file mode 100644
index 0339b85..0000000
--- a/spec/SpecRunner.html
+++ /dev/null
@@ -1,68 +0,0 @@
-
-
-
- Masked Input Plugin Tests
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/spec/lib/jquery.keymasher.js b/spec/lib/jquery.keymasher.js
index d8d9df5..bb430f6 100644
--- a/spec/lib/jquery.keymasher.js
+++ b/spec/lib/jquery.keymasher.js
@@ -1,23 +1,23 @@
/*
Key Masher plugin for jQuery (https://github.com/digitalBush/jquery.keymasher)
- Copyright (c) 2010-2013 Josh Bush (digitalbush.com)
+ Copyright (c) 2010-2014 Josh Bush (digitalbush.com)
Licensed under the MIT license
- Version: 0.3
+ Version: 0.4
*/
(function($,undefined){
//numberPad={'0':96,'1':97,'2':98,'3':99,'4':100,'5':101,'6':102,'7':103,'8':104,'9':105,'*':106,'+':107,'-':109,'.':110,'/':111},
-
+
var keys=(function(){
var defs={},
- keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`-=[]\\;',./ \t\n",
+ keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`-=[]\\;',./ \t\n\r",
shifted = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()~_+{}|:\"<>?",
noprint={shift:16,ctrl:17,meta:91,alt:18,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,
capslock:20,numlock:144,scrolllock:145,pageup:33,pagedown:34,end:35,home:36,backspace:8,
insert:45, 'delete':46,pause:19,esc:27,left:37,up:38,right:39,down:40,printscreen:44};
$.each(keys.split(''),function(index,value){
- var keyCode=value.charCodeAt(0),shift=shifted[index];
+ var keyCode=value.charCodeAt(0),shift=shifted[index];
defs[value]={keyCode:keyCode,charCode:keyCode,shift:shift};
if(shift)
defs[shift]={keyCode:keyCode,charCode:shift.charCodeAt(0),shift:value,requiresShift:index>=26};
@@ -29,39 +29,39 @@
var KeyMasher=function(elm){
var modifierState={alt: false, ctrl: false, meta: false, shift: false},
forced={};
-
+
var queueModifierEvent=function(direction,modifier,isForced){
forced[modifier]=isForced;
- modifierState[modifier]=(direction=='down');
+ modifierState[modifier]=(direction=='down');
var event=$.extend($.Event(), modifierState, {type:'key'+direction, keyCode: keys[modifier].keyCode, charCode: 0});
elm.trigger(event);
};
-
+
var queueStroke=function(key){
if($.type(key)==='string')
- key=keys[key];
+ key=keys[key];
if(key.requiresShift && !modifierState.shift)
queueModifierEvent('down','shift',true);
else if(modifierState.shift && key.shift)
key=keys[key.shift];
-
+
var ignore = !key.charCode || modifierState.alt || modifierState.ctrl || modifierState.meta,
down = $.extend($.Event('keydown'), modifierState, {keyCode: key.keyCode, charCode: 0, which:key.keyCode}),
press = $.extend($.Event('keypress'), modifierState, {keyCode: key.charCode, charCode: key.charCode, which: key.charCode}),
- up = $.extend($.Event('keyup'), modifierState, {keyCode: key.keyCode, charCode: 0, which:key.keyCode});
-
+ up = $.extend($.Event('keyup'), modifierState, {keyCode: key.keyCode, charCode: 0, which:key.keyCode});
+
elm.trigger(down);
if(!down.isDefaultPrevented() && !ignore){
elm.trigger(press);
- if(!press.isDefaultPrevented()){
+ if(!press.isDefaultPrevented() && !elm.prop("readonly")){
//need to do caret positioning
elm.val(elm.val()+String.fromCharCode(key.charCode));
}
}
elm.trigger(up);
-
+
if(forced.shift)
- queueModifierEvent('up','shift');
+ queueModifierEvent('up','shift');
};
var public={
@@ -71,13 +71,13 @@
public.type(typing);
$.each(toks,function(index,value){queueModifierEvent('up',value);});
return public;
- },
+ },
type:function(){
$.each(arguments,function(index,typing){
if($.type(typing)==='string')
$.each(typing.split(''),function(index,value){queueStroke(value);});
else
- queueStroke(typing);
+ queueStroke(typing);
});
return public;
}
@@ -91,7 +91,7 @@
fn=function(keys){keys.type(typing)};
}
return this.each(function(){
- fn(KeyMasher($(this)));
+ fn(KeyMasher($(this)));
});
};
-})(jQuery);
\ No newline at end of file
+})(jQuery);
diff --git a/spec/lib/setup.js b/spec/lib/setup.js
new file mode 100644
index 0000000..9539215
--- /dev/null
+++ b/spec/lib/setup.js
@@ -0,0 +1,14 @@
+function importGrammar(g){
+ for (var prop in g) {
+ if (g.hasOwnProperty(prop))
+ window[prop] = g[prop];
+
+ }
+}
+
+importGrammar(jasmine.grammar.FeatureStory);
+importGrammar(jasmine.grammar.GWT);
+
+var input;
+beforeEach(function(){ input = $("").appendTo("body").focus(); });
+afterEach(function(){ input.remove();});
diff --git a/src/jquery.maskedinput.js b/src/jquery.maskedinput.js
index 749da65..d0f8a2d 100644
--- a/src/jquery.maskedinput.js
+++ b/src/jquery.maskedinput.js
@@ -1,14 +1,20 @@
-function getPasteEvent() {
- var el = document.createElement('input'),
- name = 'onpaste';
- el.setAttribute(name, '');
- return (typeof el[name] === 'function')?'paste':'input';
-}
-
-var pasteEventName = getPasteEvent() + ".mask",
- ua = navigator.userAgent,
+(function (factory) {
+ if (typeof define === 'function' && define.amd) {
+ // AMD. Register as an anonymous module.
+ define(['jquery'], factory);
+ } else if (typeof exports === 'object') {
+ // Node/CommonJS
+ factory(require('jquery'));
+ } else {
+ // Browser globals
+ factory(jQuery);
+ }
+}(function ($) {
+
+var ua = navigator.userAgent,
iPhone = /iphone/i.test(ua),
- android=/android/i.test(ua),
+ chrome = /chrome/i.test(ua),
+ android = /android/i.test(ua),
caretTimeoutId;
$.mask = {
@@ -18,6 +24,7 @@ $.mask = {
'a': "[A-Za-z]",
'*': "[A-Za-z0-9]"
},
+ autoclear: true,
dataName: "rawMaskFn",
placeholder: '_'
};
@@ -27,7 +34,7 @@ $.fn.extend({
caret: function(begin, end) {
var range;
- if (this.length === 0 || this.is(":hidden")) {
+ if (this.length === 0 || this.is(":hidden") || this.get(0) !== document.activeElement) {
return;
}
@@ -65,13 +72,18 @@ $.fn.extend({
tests,
partialPosition,
firstNonMaskPos,
- len;
+ lastRequiredNonMaskPos,
+ len,
+ oldVal;
if (!mask && this.length > 0) {
input = $(this[0]);
- return input.data($.mask.dataName)();
+ var fn = input.data($.mask.dataName)
+ return fn?fn():undefined;
}
+
settings = $.extend({
+ autoclear: $.mask.autoclear,
placeholder: $.mask.placeholder, // Load default placeholder
completed: null
}, settings);
@@ -82,6 +94,8 @@ $.fn.extend({
partialPosition = len = mask.length;
firstNonMaskPos = null;
+ mask = String(mask);
+
$.each(mask.split(""), function(i, c) {
if (c == '?') {
len--;
@@ -91,6 +105,9 @@ $.fn.extend({
if (firstNonMaskPos === null) {
firstNonMaskPos = tests.length - 1;
}
+ if(i < partialPosition){
+ lastRequiredNonMaskPos = tests.length - 1;
+ }
} else {
tests.push(null);
}
@@ -99,14 +116,34 @@ $.fn.extend({
return this.trigger("unmask").each(function() {
var input = $(this),
buffer = $.map(
- mask.split(""),
- function(c, i) {
- if (c != '?') {
- return defs[c] ? settings.placeholder : c;
- }
- }),
+ mask.split(""),
+ function(c, i) {
+ if (c != '?') {
+ return defs[c] ? getPlaceholder(i) : c;
+ }
+ }),
+ defaultBuffer = buffer.join(''),
focusText = input.val();
+ function tryFireCompleted(){
+ if (!settings.completed) {
+ return;
+ }
+
+ for (var i = firstNonMaskPos; i <= lastRequiredNonMaskPos; i++) {
+ if (tests[i] && buffer[i] === getPlaceholder(i)) {
+ return;
+ }
+ }
+ settings.completed.call(input);
+ }
+
+ function getPlaceholder(i){
+ if(i < settings.placeholder.length)
+ return settings.placeholder.charAt(i);
+ return settings.placeholder.charAt(0);
+ }
+
function seekNext(pos) {
while (++pos < len && !tests[pos]);
return pos;
@@ -129,7 +166,7 @@ $.fn.extend({
if (tests[i]) {
if (j < len && tests[i].test(buffer[j])) {
buffer[i] = buffer[j];
- buffer[j] = settings.placeholder;
+ buffer[j] = getPlaceholder(j);
} else {
break;
}
@@ -147,7 +184,7 @@ $.fn.extend({
j,
t;
- for (i = pos, c = settings.placeholder; i < len; i++) {
+ for (i = pos, c = getPlaceholder(pos); i < len; i++) {
if (tests[i]) {
j = seekNext(i);
t = buffer[i];
@@ -161,12 +198,58 @@ $.fn.extend({
}
}
+ function androidInputEvent(e) {
+ var curVal = input.val();
+ var pos = input.caret();
+ if (oldVal && oldVal.length && oldVal.length > curVal.length ) {
+ // a deletion or backspace happened
+ checkVal(true);
+ while (pos.begin > 0 && !tests[pos.begin-1])
+ pos.begin--;
+ if (pos.begin === 0)
+ {
+ while (pos.begin < firstNonMaskPos && !tests[pos.begin])
+ pos.begin++;
+ }
+ input.caret(pos.begin,pos.begin);
+ } else {
+ var pos2 = checkVal(true);
+ var lastEnteredValue = curVal.charAt(pos.begin);
+ if (pos.begin < len){
+ if(!tests[pos.begin]){
+ pos.begin++;
+ if(tests[pos.begin].test(lastEnteredValue)){
+ pos.begin++;
+ }
+ }else{
+ if(tests[pos.begin].test(lastEnteredValue)){
+ pos.begin++;
+ }
+ }
+ }
+ input.caret(pos.begin,pos.begin);
+ }
+ tryFireCompleted();
+ }
+
+
+ function blurEvent(e) {
+ checkVal();
+
+ if (input.val() != focusText)
+ input.change();
+ }
+
function keydownEvent(e) {
- var k = e.which,
+ if (input.prop("readonly")){
+ return;
+ }
+
+ var k = e.which || e.keyCode,
pos,
begin,
end;
-
+ oldVal = input.val();
//backspace, delete, and escape get special treatment
if (k === 8 || k === 46 || (iPhone && k === 127)) {
pos = input.caret();
@@ -181,7 +264,9 @@ $.fn.extend({
shiftL(begin, end - 1);
e.preventDefault();
- } else if (k == 27) {//escape
+ } else if( k === 13 ) { // enter
+ blurEvent.call(this, e);
+ } else if (k === 27) { // escape
input.val(focusText);
input.caret(0, checkVal());
e.preventDefault();
@@ -189,7 +274,11 @@ $.fn.extend({
}
function keypressEvent(e) {
- var k = e.which,
+ if (input.prop("readonly")){
+ return;
+ }
+
+ var k = e.which || e.keyCode,
pos = input.caret(),
p,
c,
@@ -197,7 +286,7 @@ $.fn.extend({
if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore
return;
- } else if (k) {
+ } else if ( k && k !== 13 ) {
if (pos.end - pos.begin !== 0){
clearBuffer(pos.begin, pos.end);
shiftL(pos.begin, pos.end-1);
@@ -214,14 +303,18 @@ $.fn.extend({
next = seekNext(p);
if(android){
- setTimeout($.proxy($.fn.caret,input,next),0);
+ //Path for CSP Violation on FireFox OS 1.1
+ var proxy = function() {
+ $.proxy($.fn.caret,input,next)();
+ };
+
+ setTimeout(proxy,0);
}else{
input.caret(next);
}
-
- if (settings.completed && next >= len) {
- settings.completed.call(input);
- }
+ if(pos.begin <= lastRequiredNonMaskPos){
+ tryFireCompleted();
+ }
}
}
e.preventDefault();
@@ -232,7 +325,7 @@ $.fn.extend({
var i;
for (i = start; i < end && i < len; i++) {
if (tests[i]) {
- buffer[i] = settings.placeholder;
+ buffer[i] = getPlaceholder(i);
}
}
}
@@ -249,7 +342,7 @@ $.fn.extend({
for (i = 0, pos = 0; i < len; i++) {
if (tests[i]) {
- buffer[i] = settings.placeholder;
+ buffer[i] = getPlaceholder(i);
while (pos++ < test.length) {
c = test.charAt(pos - 1);
if (tests[i].test(c)) {
@@ -259,18 +352,31 @@ $.fn.extend({
}
}
if (pos > test.length) {
+ clearBuffer(i + 1, len);
break;
}
- } else if (buffer[i] === test.charAt(pos) && i !== partialPosition) {
- pos++;
- lastMatch = i;
+ } else {
+ if (buffer[i] === test.charAt(pos)) {
+ pos++;
+ }
+ if( i < partialPosition){
+ lastMatch = i;
+ }
}
}
if (allow) {
writeBuffer();
} else if (lastMatch + 1 < partialPosition) {
- input.val("");
- clearBuffer(0, len);
+ if (settings.autoclear || buffer.join('') === defaultBuffer) {
+ // Invalid value. Remove it and replace it with the
+ // mask, which is the default behavior.
+ if(input.val()) input.val("");
+ clearBuffer(0, len);
+ } else {
+ // Invalid value, but we opt to show the value to the
+ // user and allow them to correct their mistake.
+ writeBuffer();
+ }
} else {
writeBuffer();
input.val(input.val().substring(0, lastMatch + 1));
@@ -280,50 +386,63 @@ $.fn.extend({
input.data($.mask.dataName,function(){
return $.map(buffer, function(c, i) {
- return tests[i]&&c!=settings.placeholder ? c : null;
+ return tests[i]&&c!=getPlaceholder(i) ? c : null;
}).join('');
});
- if (!input.attr("readonly"))
- input
+
+ input
.one("unmask", function() {
input
- .unbind(".mask")
+ .off(".mask")
.removeData($.mask.dataName);
})
- .bind("focus.mask", function() {
+ .on("focus.mask", function() {
+ if (input.prop("readonly")){
+ return;
+ }
+
clearTimeout(caretTimeoutId);
var pos;
focusText = input.val();
+
pos = checkVal();
-
+
caretTimeoutId = setTimeout(function(){
+ if(input.get(0) !== document.activeElement){
+ return;
+ }
writeBuffer();
- if (pos == mask.length) {
+ if (pos == mask.replace("?","").length) {
input.caret(0, pos);
} else {
input.caret(pos);
}
}, 10);
})
- .bind("blur.mask", function() {
- checkVal();
- if (input.val() != focusText)
- input.change();
- })
- .bind("keydown.mask", keydownEvent)
- .bind("keypress.mask", keypressEvent)
- .bind(pasteEventName, function() {
- setTimeout(function() {
+ .on("blur.mask", blurEvent)
+ .on("keydown.mask", keydownEvent)
+ .on("keypress.mask", keypressEvent)
+ .on("input.mask paste.mask", function() {
+ if (input.prop("readonly")){
+ return;
+ }
+
+ setTimeout(function() {
var pos=checkVal(true);
- input.caret(pos);
- if (settings.completed && pos == input.val().length)
- settings.completed.call(input);
+ input.caret(pos);
+ tryFireCompleted();
}, 0);
});
- checkVal(); //Perform initial check for existing values
+ if (chrome && android)
+ {
+ input
+ .off('input.mask')
+ .on('input.mask', androidInputEvent);
+ }
+ checkVal(); //Perform initial check for existing values
});
}
});
-
+}));
diff --git a/templates/jquery.maskedinput.template b/templates/jquery.maskedinput.template
deleted file mode 100644
index 18f6d17..0000000
--- a/templates/jquery.maskedinput.template
+++ /dev/null
@@ -1,9 +0,0 @@
-/*
- Masked Input plugin for jQuery
- Copyright (c) 2007-{{Year}} Josh Bush (digitalbush.com)
- Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
- Version: {{version}}
-*/
-(function($) {
- {{{include "src/jquery.maskedinput.js"}}}
-})(jQuery);
\ No newline at end of file