How to Trim the Value of Angular’s Form Control
We encountered two unexpected situations recently because we didn’t trim input values.
First, Angular’s email validator performs the validation without trimming the value. In some cases, users accidentally add whitespace to the email when copying and pasting, which causes the validation to fail. Consequently, it leads to a bad UX as it’s challenging to see immediately what’s wrong:
Secondly, we have an input
where the user needs to pass a token
. When a token is pasted, the server considers it invalid if there are any white spaces.
We can solve these two cases locally by wrapping Angular’s email validator in the first case and trimming the value in the second case. However, I prefer to add the trimming functionality seamlessly when using our inputs.
As can be seen in the source code, Angular uses the BaseControlValueAccessor
class when handling inputs. Luckily, Angular also exposes this class, making it possible to use JS to override it:
We override the original registerOnChange
method and trim the value before Angular passes it to the control.
In case you haven’t read my previous article on value accessors, here is a link:
Alternatively, we can do the same thing directly in our form control instance. As an example, you might use the same technique to create inputs I described in this article:
There’s no doubt we can abstract this code and make it more generic, so it isn’t tied to trimming only, but I will leave that to you.
Follow me on Medium or Twitter to read more about Angular, and JS!