Last active
March 27, 2016 13:44
-
-
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.
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
/** | |
* 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