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>
?
To add validation to a template-driven form, you add the same validation attributes as you would with native HTML form validation. Angular uses directives to match these attributes with validator functions in the framework.
AngularJS performs form validation on the client side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not.
ng-pristine: The ng-pristine class tells that the form has not been modified by the user. This returns true if the form has not been modified by the user. Return type: Return Boolean True if the form/input field is not modified by the user else it returns False.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With