2
votes

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?

3
sure, just add a new variable.pathfinder

3 Answers

5
votes

You can use data- attributes to keep it hold. I know a jQuery version:

$(function () {
  $("#cCard").blur(function () {
    cCardNum = $(this).val();
    $(this).data("value", cCardNum);
    if (cCardNum.length > 4) {
      $(this).val(cCardNum.substr(0, 4) + "*".repeat(cCardNum.length - 4))
    }
  }).focus(function () {
    $(this).val($(this).data("value"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="cCard" />

This is a polyfill for the String.prototype.repeat function:

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null) {
      throw new TypeError('can\'t convert ' + this + ' to object');
    }
    var str = '' + this;
    count = +count;
    if (count != count) {
      count = 0;
    }
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    count = Math.floor(count);
    if (str.length == 0 || count == 0) {
      return '';
    }
    // Ensuring count is a 31-bit integer allows us to heavily optimize the
    // main part. But anyway, most current (August 2014) browsers can't handle
    // strings 1 << 28 chars or longer, so:
    if (str.length * count >= 1 << 28) {
      throw new RangeError('repeat count must not overflow maximum string size');
    }
    var rpt = '';
    for (;;) {
      if ((count & 1) == 1) {
        rpt += str;
      }
      count >>>= 1;
      if (count == 0) {
        break;
      }
      str += str;
    }
    return rpt;
  }
}
4
votes

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.

0
votes

Find working Plunker for angularjs directive to format Card Number in xxxxxxxxxxxx3456 Fromat.Plunker for Card Number Masking

angular.module('myApp', [])

   .directive('maskInput', function() {
    return {
            require: "ngModel",
            restrict: "AE",
            scope: {
                ngModel: '=',
             },
            link: function(scope, elem, attrs) {
                var orig = scope.ngModel;
                var edited = orig;
                scope.ngModel = edited.slice(4).replace(/\d/g, 'x') + edited.slice(-4);

                elem.bind("blur", function() {
                    var temp;
                    orig  = elem.val();
                    temp = elem.val();
                    elem.val(temp.slice(4).replace(/\d/g, 'x') + temp.slice(-4));
                });

                elem.bind("focus", function() {
                    elem.val(orig);
               });  
            }
       };
   })
  .controller('myCtrl', ['$scope', '$interval', function($scope, $interval) {
    $scope.creditCardNumber = "1234567890123456";
  }]);