1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

looks good, but why when you try to use the backspace it add slash and not remove chars by chars?
I have updated my answer so that slash will be removed when backspace.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.