var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.myNumber = null;
});
/**
* Based on https://gist.github.com/ShirtlessKirk/2134376
* Variant of Avraham Plotnitzky's String.prototype method mixed with the "fast" version
* see: https://sites.google.com/site/abapexamples/javascript/luhn-validation
* @author ShirtlessKirk. Copyright (c) 2012.
* Licensed under WTFPL (http://www.wtfpl.net/txt/copying)
*/
var luhnChk = function(luhn) {
var len = luhn.length,
mul = 0,
prodArr = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
],
sum = 0;
while (len--) {
sum += prodArr[mul][parseInt(luhn.charAt(len), 10)];
mul ^= 1;
}
return sum % 10 === 0 && sum > 0;
};
app.directive('luhnCheck', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attributes, ngModel) {
function luhnCheck(value) {
ngModel.$setValidity('luhn-check', luhnChk(value));
return value;
}
ngModel.$parsers.push(luhnCheck);
ngModel.$formatters.push(luhnCheck);
}
};
})
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Luhn Check directive</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script src="http://code.angularjs.org/1.2.25/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h2>Luhn Validator</h2>
<div ng-form='myForm'>
<input type='text' ng-model='myNumber' name='number' luhn-check />
<div ng-show="myForm.number.$error['luhn-check']" class='error'>Error: failed Luhn check</div>
</div>
<div>
<h4>Valid numbers</h4>
<ul>
<li>4242424242424242</li>
<li>4012888888881881</li>
<li>5200828282828210</li>
<li>378282246310005</li>
<li>6011111111111117</li>
<li>30569309025904</li>
</ul>
</div>
</body>
</html>
/* Put your css in here */
.error{
background: red;
color: white;
padding: 5px 10px;
}
input{
border: 1px solid gray;
padding: 5px 15px;
border-radius: 5px;
font-size: 20px;
font-weight: bold;
}
See http://www.alexlindgren.com/archive/custom-angularjs-directive-for-luhn-validation/