Search code examples
javascriptangularjsformsinputmask

Mask credit card input on blur


I have an input in my form that takes a credit card number.

  <input type="text" class="form-control" name="CCnumber" ng-model="CCnumber" ng-blur="balanceParent.maskCreditCard(this)">

On blur, I'd like to mask the credit card input like so:

4444************

And then on focus, I'd like to return the original credit card number:

4444333322221111

Using ng-blur, I'm able to do simple javascript to return a masked input.

    vm.maskCreditCard = function(modalScope) {
      if(modalScope.CCnumber){
      var CCnumber = modalScope.CCnumber.replace(/\s+/g, '');
      var parts = CCnumber.match(/[\s\S]{1,4}/g) || [];
      for(var i = 0; i < parts.length; i++) {
        if(i !== 0) {
        parts[i] = '****';
      }
    }
    modalScope.CCnumber = parts.join("");
  }
};

My problem is getting that number back once the user focuses on the input once more. Is there a way to preserve the inital value of the input while also masking it?


Solution

  • I'd create an attribute directive for this. Angular best practice is to manipulate the DOM inside a directive instead of a controller.

    In your case, when you bind the blur event to the element, you should save the current value into a variable. You can then access this variable when you bind the focus event.

     angular.module('CreditApp', [])
         .directive('maskInput', function() {
             return {
                 restrict: "A",
                 link: function(scope, elem, attrs) {
                     elem.bind("blur", function() {
                         var number = elem.val();
                         elem.val(elem.val().slice(0,4) + elem.slice(4).replace(/\d/g, '*'));
                     });
                     elem.bind("focus", function() {
                         elem.val(number);
                    });
                 }
            }
      });
    

    I just created a plunkr for this

    http://plnkr.co/edit/ZywTmF7xfz2FyvRULLjL?p=preview

    Try typing a credit card number in the input box and click outside the box. This is the blur event and the credit card number will be masked. Now, click inside the box again, and the value will be restored.