Angular form validation
Today I am writing a blogpost about Angular form validation.
one of AngularJS strenghts is client-side form validation. In this article I will go through this with in the end of the article an example that you can check out and play with it.
The client-side validation is a very helpful thing in Angular that will safe you a lot of time when making a form. Angular will offer you a client-side form validation.
Be aware that only client-side validation alone cannot secure user input. Server side validation is also necessary.
The validation will monitor the state of the form and input fields. When the user will type in his data, the form will immediately give a response if the data is valid or invalid. For example; if the user typed in a name that is invalid for any reason the form will give a response with the reason why it is invalid.
Angular will automaticcaly updated the form state and input state.
Input fields have the following states:
$untouched The field has not been touched yet $touched The field has been touched $pristine The field has not been modified yet $dirty The field has been modified $invalid The field content is not valid $valid The field content is valid They are all properties of the input field, and are either true or false.
Forms have the following states:
$pristine No fields have been modified yet $dirty One or more have been modified $invalid The form content is not valid $valid The form content is valid $submitted The form is submitted
A clear example to show that Angular immediately updates the form state is the $invalid property.
We want our submit button to be disabled when our form is “$invalid”. And only want to enable it when the form is valid. With just a little bit of code (ng-disabled) we can realise this.
So when the submitted is enabled it means that we have a valid email and username.
<button class="btn btn-primary" type="submit">Submit</button>
If you want to show an error message when your username is not valid you can add “ng-show” with the credentials you want. For example:
<input class="form-control" name="username" required="" type="text" /> <p class="help-block">Username is too short.</p>
This will give an error when the user name doesn’t fit the requirements you set. When you add Bootstrap to your project you can use the classes they provide. This will give us that nice colour around our form-group.
Also a good practice is to connect the form to a form submit function on the controller using ng-submit, rather than allowing the default form submit to occur. This is not necessary but is usually used, as the input variables are already available on the scope and so available to your submit function.
<form name="userForm" novalidate="">
Below I will show you 2 examples of how a invalid form looks like and how a valid form looks like.