bernlt
bernlt

Reputation: 445

Angular input field data format

Angular template input field should take maxLength: mm/dd/yyyy = 10;

 <input
  class="form-control"
  type="text"
  appInputMask
  formControlName="expiryDate"
  id="expiry-date"
  maxlength="4"
/>

Found this Directive appInputMask that does the job form the format MM/YY, but I need MM/DD/YYYY.

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[formControlName][appInputMask]',
})
export class InputMaskDirective {

  @HostListener('input', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;

    const trimmed = input.value.replace(/\s+/g, '').slice(0, 4);
    if (trimmed.length > 3) {
      return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2)}`);
    }
  }
  
}

I'm playing around trying to get the correct format, but not successfull, thanks for any help.

https://stackblitz.com/edit/angular6-mask-34t827input-6rxqq9?file=app%2Fapp.component.html

Upvotes: 1

Views: 697

Answers (1)

N.F.
N.F.

Reputation: 4202

First, set maxLength="8" in your template.

<input
  class="form-control"
  type="text"
  appInputMask
  formControlName="expiryDate"
  id="expiry-date"
  maxlength="8"
/>

Then modify your directive like below.

import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[formControlName][appInputMask]',
})
export class InputMaskDirective {
  @HostListener('input', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;

    const trimmed = input.value.replace(/[\s+/]/g, '').slice(0, 8);
    if (trimmed.length > 7) {
      return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2, 4)}/${trimmed.slice(4)}`);
    } else {
      return (input.value = trimmed);
    }
  }
}

Stackblitz sample.

Upvotes: 1

Related Questions