Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>?

like image 302
Wojtek Avatar asked Feb 28 '14 15:02

Wojtek


People also ask

How to add validation in template driven 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.

How are validations implemented in AngularJS?

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.

What is pristine in Angular?

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.


1 Answers

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

like image 119
Silvio Lucas Avatar answered Oct 21 '22 06:10

Silvio Lucas