Skip to main content

Masking Inputs

Jeff Gonzalez
# Masking Inputs

Case: You want to obscure sensitive data on the screen to confound shoulder surfers all up in your business, but also not create accessibility roadblocks.

Certain data should be occluded on the screen when viewing that data. When that data is provided by the user, having the input apply the mask can be frustrating. Using the ngx-mask library, we can mask inputs on the screen, but not mask the data when it is provided by the user, and only mask it when the input loses focus, or on request by the user.

Process

  1. Install the library
npm install ngx-mask
  1. Import the library into your module
import { NgModule } from "@angular/core";
import { ReactiveFormsModule } from "@angular/forms";
import { BrowserModule } from "@angular/platform-browser";
import { NgxMaskModule } from "ngx-mask";

import { AppComponent } from "./app.component";
import { EntryFormComponent } from "./entry-form/entry-form.component";

@NgModule({
declarations: [AppComponent, EntryFormComponent],
imports: [
BrowserModule,
ReactiveFormsModule,
NgxMaskModule.forRoot(),
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
  1. Use the library in your component

See the Stackblitz for the form.component.ts and the form.component.html.

  1. The pattern referenced in the template is defined in the component class.

Template

/src/app/entry-form/entry-form.component.html
<input
type="text"
id="ssn"
(focus)="toggleShowSsn()"
(blur)="ssnBlur()"
formControlName="ssn"
[patterns]="ssnPattern"
[hiddenInput]="hideSsn"
mask="YYY-YY-SSSS"
/>

Component

/src/app/entry-form/entry-form.component.ts
ssnPattern = {
Y: { pattern: new RegExp("\\d"), symbol: "X" },
S: { pattern: new RegExp("\\d") },
};
tip

This pattern says "replace any instances of 'Y' with an X and leave any instances of 'S' alone."