- Getting started with AngularJS
- Creating an AngularJS Controller
- The AngularJS $scope is not the MVC Model
- Using repeating elements in AngularJS
- Filtering the data in an AngularJS ngRepeat element
- Using the AngularJS FormController to control form submission
- Creating an AngularJS Directive
- Using the DOM in an AngularJS application
- To SPA or not to SPA
One of the more frequent things you have to do in a forms over data application, the kind where AngularJS really shines, is create and validate data entry forms. The basics of this are pretty easy, just create a controller, add a model to the $scope, create an HTML form and add ng-model input elements for each property the user should enter. No big deal there.
However it would be nice if we could do basic validation in the form and disable a submit button if the form is invalid or the user hasn’t made any changes yet. It turns out this is quite easy to do in AngularJS as each HTML from element automatically creates a FormController and this contains a number of properties that tell us what the status of the form is. In this case we are interested in the $pristine which tells us if the user made any changes and the $invalid which tells us the form is considered to be invalid.
Add to this the ng-disabled directive which we can use to automatically disable an input control and we have the last missing piece to automatically enable/disable the form submit button.
we can add some more form validation to this if we want. In the example above I have added the ng-required attribute to indicate that the first and last name are required. I have also use the HTML5 input type=”email” for the input control to enter the users email address. AngularJS understands there new HTML5 input types and will recognize the field as invalid if the data entered doesn’t resemble an email address. IN fact it does a slightly better job than most browsers as Chrome considers “a@a” a valid email address but AngularJS wants us to enter at least a bit more with “firstname.lastname@example.org”.
If we want we can show extra error messages is specific input fields fail validation like this: