Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  158] [ 5]  / answers: 1 / hits: 6514  / 11 Years ago, mon, february 10, 2014, 12:00:00

Using angularjs, I'm not satisfied with the ng-maxlength tag. I want the input field to block the user from entering additional characters when the max length has been hit. So instead of ng-maxlength, I tried writing a directive that would validate the input on keydown/keypress:



.directive('vldMaxLength', function() {
return function (scope, element, attr) {
element.bind('keydown keypress', function (event) {
if(event.target.value.length >= 10 && (event.which !== 8 && event.which !== 46)) {
event.preventDefault();
}
});
};
})


This works decently, but the user is unable to highlight a portion of the string and replace with different characters. Maybe there's something I can add to the directive to allow for this? Or maybe there's an easier way to get this functionality instead of using a directive.



JSFiddle: http://jsfiddle.net/DwKZh/147/


More From » forms

 Answers
1

You could use the straight HTML version:



<form action=demo_form.asp>
Username: <input type=text name=usrname maxlength=10><br>
<input type=submit value=Submit>
</form>

[#47865] Monday, February 10, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerardob

Total Points: 571
Total Questions: 115
Total Answers: 96

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;