Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent user from entering additional characters when maximum length reached

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/

like image 227
jlewkovich Avatar asked Dec 03 '22 20:12

jlewkovich


1 Answers

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>
like image 181
Codeman Avatar answered Jan 04 '23 23:01

Codeman