Trim on Blur

Posted on Oct 19, 2021

Your Angular application is asking for some data to the user. There you’ve some fields, with some of them under validation. You could have a mail address, or even a mobile phone number. Maybe you designed some regular expressions to address that need and they work as expected.

But then a bug appears on your backlog. User reported that for some reason the validation has been triggered on a form. You’ll start investigating, but nothing seems to be wrong. Then you realize that in case of mails of phone numbers, there could room for a copy’n’paste habit from the user. That means there’s room for trailing spaces in the value!

At a first look it seems to be a easy-to-fix issue: just trim the value when the blur event is fired. But if you’ve lots of fields that needs to be enhanced with this behavior…it could end up in a lot of changes!

Then an idea come up in my mind: let’s trim on form changes, with a debouncing - because blur is a UI event, while we’re watching for the form value changes.

const trimFormValue = (formGroup: FormGroup, debouncing: number = 2000): Subscription =>
  formGroup.valueChanges.pipe(debounceTime(debouncing)).subscribe(formValue => {
    Object.entries(formValue)
      .filter(([, value]) => typeof value === 'string')
      .map(([formControlName, value]) => [formGroup.controls[formControlName], value] as [FormControl, string])
      .forEach(([formControl, value]) => formControl.setValue(value.trim()));
  });

This small helper is returning a subscription: remember to take care of it and unsubscribe from the stream when its time is over - maybe ngOnDestroy is the right time.

So in the case of few forms - with possibly hundreds of fields - we’ve now the chance to avoid trailing whitespaces without too much code changes. Great!