1

I'm working a directive to autotab between elements whenever the element's maxLength is hit. But first, I'm trying to figure out how to make sure that an element can't have a value whose length is greater than the element's maxlength.

Here's what I've tried so far:

  if (el.value.length >= el.maxLength) {
    el.value = el.value.substr(0, el.maxLength);
  }

If I set a breakpoint and step through it, right after executing this, el.value is being set correctly, but in the view it's still allowing the user to type.

Alex Kibler
  • 4,674
  • 9
  • 44
  • 74

1 Answers1

0

Dynamically modifying validator attributes is currently not supported. They have to be statically added (no [] binding) and are only read once when the control instance is built.

You can do this with forms using FormBuilder and a validator that has a reference to other values that might influence the validation like shown in How to change validation of a control after it has been initiated?

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I don't really consider this a validator though, I'm just trying to force a value – Alex Kibler Jun 22 '16 at 13:24
  • See also http://stackoverflow.com/questions/37800841/input-mask-fields-in-angular2-forms Your question is not clear enough to me to make better suggestions – Günter Zöchbauer Jun 22 '16 at 13:27
  • I'm not sure how I can clarify it. Whenever the user types in an input, I'm checking if the input's value's length is greater than the input's maxlength. If it is, I want to truncate the input's value to match the maxlength. So if I have a field whose maxlength is 5, the user can't type more than 5 characters. In jQuery, I would have done `$("#element").val($("#element").val().substr(0,maxlength))` – Alex Kibler Jun 22 '16 at 13:30
  • Sounds like the approach in the linked question should fit. – Günter Zöchbauer Jun 22 '16 at 13:31
  • Hm, yeah, I think it might be. I'll check it out now. Thanks! – Alex Kibler Jun 22 '16 at 13:32
  • You can add an `@Input()maxLength;` to get the setting from the element. – Günter Zöchbauer Jun 22 '16 at 13:34