Let’s continue our dive into Angular form validation capabilities. So far, we have seen how to display custom feedback to the user based on basic HTML validation features. Today, let’s see how to customize the validation itself.
The good news is that all we need is a function. That function takes a FormControl
as a parameter and returns null
if the value entered by the user is valid. If the value is invalid, we return a ValidationErrors object, any key/value object we want.
Here’s an example:
Pretty straightforward, right? If the zip code is wrong, we return an object with a custom error message. Otherwise, we return null
.
Of course, we can validate more precisely by adding several different checks and specific error messages for each case:
Then to have a specific input use that validation function, we can pass it as a parameter to the FormControl
constructor like so:
And then such FormControl
gets bound to the proper input in our HTML template (this is the approach for reactive forms – we will cover a method that works for template-driven forms tomorrow). We can then add some error handling by using the errors property of our FormControl
, which is going to have the ValidationErrors
object returned from our validation function:
Now our form provides custom feedback using our custom validation function:
You can access the code for the above example on Stackblitz.