4

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/

1 Answer 1

17

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>
Sign up to request clarification or add additional context in comments.

2 Comments

@mila if you're using Angular, use the Angular way of limiting field length.
@ArlenBeiler ng-maxlength: docs.angularjs.org/api/ng/directive/input it gives more information to the data model than a simple HTML solution so you can give feedback to the user, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.