Introduction to Form Validation and States
In the previous blog I asked you to create a simple form. I received more mails that gives me some pleasure to start this new form validation post (Review is in progress. Will publish the best one soon). Thus We have seen how to create forms, and enable (and leverage) data-binding to get our data in and out of the UI. Now let’s proceed to see how else AngularJS can benefit us when working with forms, and especially with validation and various states of the forms and inputs:
In this example, we reworked our old example to add some validation. In particular, we want to disable the Submit button if the user has not filled out all the required fields. How do we accomplish this?
1. We give the form a name, which we can refer to later. In this case, it is myForm.
2. We leverage HTML5 validation tags and add the required attribute on each input field.
3. We add a validator, ng-minlength, which enforces that the minimum length of the value in the input field for the username is four characters.
4. On the Submit button, we add an ng-disabled directive. This disables the element if the condition is true.
5. For the disable condition, we leverage the form, which exposes a controller with the current state of the form. In this case, we tell the button to disable itself if the form with the name myForm is $invalid.
When you use forms (and give them names), AngularJS creates a FormController that holds the current state of the form as well as some helper methods. You can access the FormController for a form using the form’s name, as we did in the preceding example using myForm. Things that are exposed as the state and kept up to date with data-binding are shown here.
|$invalid||AngularJS sets this state when any of the validations (required, ng-minlength, and others) mark any of the fields within the form as invalid.|
|$valid||The inverse of the previous state, which states that all the validations in the form are currently evaluating to correct.|
|$pristine||All forms in AngularJS start with this state. This allows you to figure out if a user has started typing in and modifying any of the form elements. Possible usage: disabling the reset button if a form is pristine.|
|$dirty||The inverse of $pristine, which states that the user made some changes (he can revert it, but the $dirty bit is set).|
|$error||This field on the form houses all the individual fields and the errors on each form element. We will talk more about this in the following section|
Each of the states mentioned in the table (except $error) are Booleans and can be used to conditionally hide, show, disable, or enable HTML elements in the UI. As the user types or modifies the form, the values are updated as long as you are leveraging ngmodel and the form name.
In the next blog I will explain the ways by which we can handle these errors. Happy learning!! 🙂