Search code examples
angularjsformsvalidationcounterng-maxlength

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.


Solution

  • 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