Skip to content

Instantly share code, notes, and snippets.

@barzik
Last active March 27, 2016 13:44
Show Gist options
  • Save barzik/d66d30d164b8bf5bb527 to your computer and use it in GitHub Desktop.
Save barzik/d66d30d164b8bf5bb527 to your computer and use it in GitHub Desktop.
The max-length-escaped directive testing the length against escaped value. Prevent sending exceeding escaped length input to server\API that enforce size.
/**
* The max-length-escaped directive testing the length against escaped
* value. Prevent sending exceeding escaped length input to server\API that enforce size.
*
* Usage:
* <input type="text" max-length-escaped="250" /> || <textarea max-length-escaped="1000"></textarea>
*
* License: MIT
*/
angular.module('utils.maxLengthEscaped')
.directive('maxLengthEscaped', [function() {
return {
restrict: 'A',
require:'ngModel',
link: function(scope, element, attr, ngModel) {
var limit = attr.maxLengthEscaped;
ngModel.$parsers.push(function(newValue){
var escapedValue = encodeURI(newValue),
escapedLength = escapedValue.length || 200;
if(escapedLength > limit) {
newValue = decodeURI(escapedValue.substr(0, limit));
ngModel.$viewValue = newValue;
ngModel.$render();
}
return newValue;
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment