在模糊上屏蔽信用卡输入

Kyl*_*ase 2 javascript forms input mask angularjs

我的表单中有一个输入,它需要一个信用卡号。

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

在模糊时,我想像这样屏蔽信用卡输入:

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

然后在焦点上,我想返回原始信用卡号:

4444333322221111

使用 ng-blur,我可以执行简单的 javascript 来返回屏蔽输入。

    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("");
  }
};
Run Code Online (Sandbox Code Playgroud)

我的问题是一旦用户再次关注输入,就可以恢复该数字。有没有办法在保留输入的初始值的同时屏蔽它?

小智 5

您可以使用data-属性来保持它。我知道一个 jQuery 版本:

$(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"));
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="cCard" />
Run Code Online (Sandbox Code Playgroud)

这是该String.prototype.repeat功能的 polyfill :

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;
  }
}
Run Code Online (Sandbox Code Playgroud)