Creating first form validation

With AngularJS you can easily create forms with the validation support. The form will always be synchronized to its model with the two-way data binding mechanism, through the ngModel directive.

Creating our first form
The HTML language has an element called form that surrounds the fields in order to pass them to the server. It creates a boundary and isolates the form as a single and unique context. With AngularJS, we will do almost the same thing. We need to surround our fields with the form element and give a name to each field to refer to it in the future.

Adding the form to our angular application.
index.html
<form name="carForm">
<input type="text" name="plateField" ng-model="car.plate" placeholder="What's the plate?" />
</form>
To perform validation properly, avoid using the name that has already been used inside the ngModel directive.

Basic validation
The validation process is quite simple and relies on some directives like ngRequired directive. This directive could be attached to any field of the form in order to intimate the validation process that the field is actually required.
<input type="text" name="plateField" ng-model="car.plate" placeholder="What's the plate?" ng-required="true" />
We could the ngMinlength and ngMaxlength directives for validation which is used to define a minimum or maximum limit to each field.

An example to use required parameter and also have minimum and maximum limits.
<input type="text" name="plateField" ng-model="car.plate" placeholder="What's the plate?" ng-required="true" ng-minlength="6" ng-maxlength="10" />
We can add a regular expression to validate the format of the plate using the ngPattern directive.
<input type="text" name="plateField" ng-model="car.plate" placeholder="What's the plate?" ng-required="true" ng-minlength="6" ng-maxlength="10" ng-pattern="/[A-Z]{3}[0-9]{3,7}/" />
We can do it using the object $valid. It will be defined based on the directives of each field. If any of these violate the directives definition, the result will be false. Also, the $invalid object can be used.
<button ng-click="park(car)" ng-disabled="carForm.$invalid">
Park
</button>
If the plate is not valid, the following alert should be displayed:
<alert ng-show="carForm.plateField.$invalid" topic="Something went wrong!">
The plate is invalid!
</alert>

However, there is a problem with this approach. The alert is displayed even if we type nothing and this might confuse the user.
1