jlewkovich
jlewkovich

Reputation: 2775

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/

Upvotes: 4

Views: 7125

Answers (1)

Codeman
Codeman

Reputation: 12375

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>

Upvotes: 17

Related Questions