Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
bunzli committed Oct 15, 2013
0 parents commit f90dbf9
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
28 changes: 28 additions & 0 deletions bower.json
@@ -0,0 +1,28 @@
{
"name": "angular-platanus-rut",
"version": "0.0.1",
"authors": [
"Jaime Bunzli <jpbunzli@gmail.com>"
],
"description": "Chilean RUT module for angular",
"license": "MIT",
"homepage": "https://github.com/angular-platanus/rut",
"repository": {
"type": "git",
"url": "git://github.com/angular-platanus/rut.git"
},
"main": "./src/rut.js",
"ignore": [
"**/.*",
"Gruntfile.js",
"karma.conf.js",
"package.json",
"test",
"src",
".travis.yml"
],
"devDependencies": {
"angular": "*",
"angular-mocks": "*"
}
}
67 changes: 67 additions & 0 deletions src/rut.js
@@ -0,0 +1,67 @@
angular.module('platanus.rut')
.directive('rut', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var clean = function(value) {
if(!value) return '';

return value.toString().replace(/[^0-9kK]+/g,'').toUpperCase();
};

var validate = function(value) {
if(!value) return true;
value = clean(value);

var t = parseInt(value.slice(0,-1), 10), m = 0, s = 1;
while(t > 0) {
s = (s + t%10 * (9 - m++%6)) % 11;
t = Math.floor(t / 10);
}
var v = (s > 0) ? (s-1)+'' : 'K';

return (v == value.slice(-1));
};

var format = function(value) {
var formatValue = [];
value = clean(value);

var reverseValue = value.split('').reverse();

for(var i = 0; i < reverseValue.length; i++) {

if(i === 1)
formatValue.push("-");
else if((i-1) % 3 === 0)
formatValue.push(".");

formatValue.push(reverseValue[i]);
}

return formatValue.reverse().join('');
};

//For DOM -> model validation
ngModel.$parsers.unshift(function(value) {
var valid = validate(value);
ngModel.$setValidity('rut', valid);

return valid ? clean(value) : undefined;
});

//For model -> DOM validation
ngModel.$formatters.unshift(function(value) {
var valid = validate(value);
//ngModel.$setValidity('rut', valid);

return format(value);
});

elem.bind('blur', function() {
ngModel.$viewValue = format(ngModel.$modelValue);
ngModel.$render();
});
}
}
});

0 comments on commit f90dbf9

Please sign in to comment.