AngularJS <input> validation with no enclosing <form>
Is it possible in Angular to validate a single, isolated <input>
in a similar way the forms are validated? I'm thinking about something like this:
<div class="form-group">
<input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5">
<span class="error" ng-show="myInput.$error.maxlength">Too long!</span>
</div>
The example above doesn't work. Enclosing it in a <form>
and replacing ng-show
with ng-show="myForm.myInput.$error.maxlength"
helps.
Is it possible to do this without using <form>
?
Solution 1:
You may use the ng-form angular directive (see docs here) to group anything, even outside a html form. Then, you can take advantage from angular FormController.
<div class="form-group" ng-form name="myForm">
<input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5">
<span class="error" ng-show="myForm.myInput.$error.maxlength">Too long!</span>
</div>
Example