如何使角遮罩与各种信用卡一起使用?

trs*_*trs 2 javascript masking angularjs angular-ui

我在信用卡字段上使用 AngularUI Mask ( https://github.com/angular-ui/ui-mask )。

<input type="text" placeholder="xxxx-xxxx-xxxx-xxxx" ui-mask="9999-9999-9999-9999" ng-model="card.number">

但是,根据 Stripe ( https://stripe.com/docs/testing ) 的说法,并非所有卡片都有 16 位数字。如何允许用户输入 14 到 16 位数字并自动将其格式化为:

  • 美国运通的 xxxx-xxxxxx-xxxxx
  • xxxx-xxxx-xxxx-xx 用于 Diners Club
  • xxxx-xxxx-xxxx-xxxx 用于其他一切

Plnkr:http ://plnkr.co/edit/Qx9lv7t4jGDwtj8bvQSv?p=preview

ndm*_*web 6

最简单的方法是使用控制器范围内的变量作为掩码值。观察 cc 编号的值并根据卡的类型动态更改掩码。为此,您必须禁用对ui-maskvia 的验证ui-options。然后$scope.$watch()卡号的值随着它的变化而变化。

使用基本的正则表达式匹配(感谢@stefano-bortolotti的要点)来确定卡片的类型。对于更强大的方法,您可以使用更深入的库,如credit-card-type

function getCreditCardType(creditCardNumber) { 
  // start without knowing the credit card type
  var result = "unknown";

  // first check for MasterCard
  if (/^5[1-5]/.test(creditCardNumber)) {
    result = "mastercard";
  } 
  // then check for Visa
  else if (/^4/.test(creditCardNumber)) {
    result = "visa";
  }
  // then check for AmEx
  else if (/^3[47]/.test(creditCardNumber)) {
    result = "amex";
  } 
  // then check for Diners
  else if (/3(?:0[0-5]|[68][0-9])[0-9]{11}/.test(creditCardNumber)) { 
    result = "diners"
  }
  // then check for Discover
  else if (/6(?:011|5[0-9]{2})[0-9]{12}/.test(creditCardNumber)) {
    result = "discover";
  } 

  return result;
}
Run Code Online (Sandbox Code Playgroud)

然后,更改掩码变量以适应该特定卡片类型的要求。

function getMaskType(cardType){
  var masks = {
    'mastercard': '9999 9999 9999 9999',
    'visa': '9999 9999 9999 9999',
    'amex': '9999 999999 99999',
    'diners': '9999 9999 9999 99',
    'discover': '9999 9999 9999 9999',
    'unknown': '9999 9999 9999 9999'
  };
  return masks[cardType];
}
Run Code Online (Sandbox Code Playgroud)

将它们全部放在您的控制器中。

myApp.controller("myCtrl", function($scope) {
  $scope.cc = {number:'', type:'', mask:''};
  $scope.maskOptions = {
    allowInvalidValue:true //allows us to watch the value
  };
  $scope.$watch('cc.number', function(newNumber){
    $scope.cc.type = getCreditCardType(newNumber);
    $scope.cc.mask = getMaskType($scope.cc.type);
  });
});
Run Code Online (Sandbox Code Playgroud)

HTML 将如下所示:

<input ng-model="cc.number" ui-mask="{{cc.mask}}" ui-options="maskOptions" />
Run Code Online (Sandbox Code Playgroud)

示例:https : //jsfiddle.net/gq42wbL5/18/