Created
May 29, 2014 17:31
-
-
Save tshaddix/112f2dfd98a8efe2da28 to your computer and use it in GitHub Desktop.
Angular cents directive for validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by tyler on 5/1/14. | |
*/ | |
(function(){ | |
'use strict'; | |
angular.module('fsApp') | |
.directive('nsCents', [function () { | |
return { | |
restrict: 'A', | |
require : 'ngModel', | |
link: function postLink(scope, element, attrs, ctrl) { | |
ctrl.$parsers.unshift( | |
function(viewValue) { | |
if(!_.isUndefined(viewValue) && viewValue !== ''){ | |
// remove spaces and commas and dollar sign | |
var _r = viewValue.toString().replace(/\s|,|\$/g, ''); | |
if(_r.length && _r[0] === '.'){ | |
_r = '0' + _r; | |
} | |
var _rs = _r.split('.'); | |
var _f = parseInt(_rs[0]); | |
var _s = 0; | |
if(_rs.length > 1){ | |
if(_rs[1].length === 1){ | |
_rs[1] += '0'; | |
} | |
_s = parseInt(_rs[1].toString().substring(0, 2)); | |
} | |
var _n = (_f * 100) + _s; | |
if(!isNaN(_n)){ | |
ctrl.$setValidity('nsCents', true); | |
return _n; | |
} else { | |
ctrl.$setValidity('nsCents', false); | |
return undefined; | |
} | |
} else { | |
ctrl.$setValidity('nsCents', true); | |
return undefined; | |
} | |
} | |
); | |
ctrl.$formatters.unshift(function(modelValue){ | |
if(!_.isUndefined(modelValue)){ | |
return (modelValue/100).toFixed(2); | |
} else { | |
return undefined; | |
} | |
}); | |
} | |
}; | |
}]); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment