Search code examples
angularjsmaskangular-ui

angularjs mask override characters


I have a mask setup on a date field using the angular-ui masks module like so:

<input type="text"
     id="date"
     ng-model="transaction.date"
     ui-mask="99/99/9999" />

If I have 30/05/2013 in the field and want to change that to 10/05/2013 by simply putting a '1' at the start it pushes all the characters over so it becomes 13/00/5201.

Is there way to force ui-mask to overwrite the character insted of inserting it? (This would save someone from hitting 'delete' then the character.

Example: http://jsfiddle.net/5NbD7/ If you type '30' at the front of my example you will end up with 30/01/0120 I would rather it override the characters and produce 30/01/2010


Solution

  • I don't know it there is an easier way, but you try the following :

    • You will need to download mask.js, unminified, from source and link it in your html, if you haven't already done so.

    https://rawgithub.com/angular-ui/ui-utils/master/modules/mask/mask.js

    • Then you will need to modify the source code of mask.js like this (seach for the comment //Update Values and put this code below) :

    ...

             // Update values
              if (oldValueUnmasked !== "" && oldValueUnmasked!==valUnmasked && !isDeletion) {
                 var charIndex = maskCaretMap.indexOf(caretPos);
                 if (charIndex === -1) {
                   charIndex = maskCaretMap.indexOf(caretPos+1);
                 }
                 valUnmasked=valUnmasked.substr(0,charIndex).concat(oldValueUnmasked.substr(charIndex,valUnmasked.length));
               }
    

    ...

    Now, before updating the value, mask will do a concatenation of the characters in the old value and those in the new value, depending on the position of the cursor (caret).

    It's by no means an ironproof solution, but it should give you an idea of where to look if you want to customise the input more or check that this change does not break anything else.

    Fiddle: http://jsfiddle.net/CALvj/