Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS text input validation with counter

I'm developing an app containing a form which has a text input with ng-model="description". Now I want to validate this text input using ng-maxlength="50" and required. This works fine, but I also want to add a character counter (like 67/50) shown at all times. I'm using the following code to display the counter: {{description.length || 0}}/50

The issue with this, however, is that description.length doesn't return a value when it's greater than 50, because description input is invalid. In my scenario the counter would default to 0/50 when there's no input (and that's fine) but also when input exceeds max length.

I would also like to display my counter in red when the input length's invalid, but that shouldn't be too hard using angular validation css classes.

Of course I could provide custom validation, but I'm positive there's an easier solution.

like image 851
dduupp Avatar asked Feb 14 '15 11:02

dduupp


1 Answers

Use the form element $viewValue instead like this:

<form name='form'>

  <input type="text" name='description' ng-model='description' ng-maxlength="50">
  {{form.description.$viewValue.length || 0}}/50
</form>

See this plunker

like image 154
Maurice Avatar answered Oct 13 '22 14:10

Maurice