Last active
August 29, 2015 14:08
-
-
Save shunjikonishi/2dbe5e8eab1ebd08e434 to your computer and use it in GitHub Desktop.
AngularJS: Custom maxlength and minlength with surrogate pair support.(1.2.x)
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
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