Angular provides all of the pieces we need to perform form validation in the browser. One of those pieces are input validators.
true if the input is valid, or
otherwise. Input validators are then wrapped in directives which can be applied to
form tags (such as the
<input> tag). Many powerful input validators are include with Angular. Please refer to Angular’s guide on
forms for more information on how form validation works.
For a current project, I wanted to validate that a user’s password was equal to their confirmed password field; a very common use case for websites that perform authentication. It was easy to write an Angular custom form validator which will fulfilled our requirements.
I started off by declaring a directive named
equal. The directive is responsible for registering the custom validator; meaning
we will need to require the
ngModel directive. By requiring the
ngModel directive, we can add our custom validator to the
Lastly, we register a
$watch on the two way bound
equal scope variable. This allows us to trigger a new ngModel validation sequence
every time the value of
Here is the finished directive:
Once the directive is complete, it just needs to be added to the form. The directive should be added as an attribute
to the form field you want to check for equality. Make sure to pass in the scope variable you want to compare against:
Here is how I used the
equal directive with a password and password confirmation field:
Here are the full contents of index.html; showing how to check for validation errors with the
##Demo Here is the full working example, hosted on Plunker: