Skip to content

Instantly share code, notes, and snippets.

@shunjikonishi
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shunjikonishi/2dbe5e8eab1ebd08e434 to your computer and use it in GitHub Desktop.
Save shunjikonishi/2dbe5e8eab1ebd08e434 to your computer and use it in GitHub Desktop.
AngularJS: Custom maxlength and minlength with surrogate pair support.(1.2.x)
angular.module('directive')
.directive("spMaxlength", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var max = parseInt(attrs.spMaxlength || 0, 10);
ctrl.$parsers.unshift(function(viewValue) {
var len = viewValue ? viewValue.length - (viewValue.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)||[]).length : 0;
if (len <= max) {
ctrl.$setValidity("maxlength", true);
return viewValue;
} else {
ctrl.$setValidity("maxlength", false);
return undefined;
}
});
}
};
})
.directive("spMinlength", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var min = parseInt(attrs.spMinlength || 0, 10);
ctrl.$parsers.unshift(function(viewValue) {
var len = viewValue ? viewValue.length - (viewValue.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)||[]).length : 0;
if (len == 0 || len >= min) {
ctrl.$setValidity("minlength", true);
return viewValue;
} else {
ctrl.$setValidity("minlength", false);
return undefined;
}
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment