hey i want to add dashes when user enter date of birth manually. like this 08-18-2019 but i cannot be able to do this
public dateOfBirth: { year: number; month: number; day: number };
html file
<input
ngbDatepicker
dobMask
#d="ngbDatepicker"
#dobF="ngModel"
class="form-control input-underline input-lg"
id="dob"
[(ngModel)]="dateOfBirth"
placeholder="mm-dd-yyyy"
name="dp"
[ngClass]="{
invalid:
(dobF.value === null || isString(dobF.value) || futureDate) && dobF.touched
}"
required
/>
i tried directive but result is something like this 11---------3
here is my directive code
@Directive({
selector: '[dobMask]'
})
export class DobDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
let trimmed = input.value.replace(/\s+/g, '');
if (trimmed.length > 8) {
trimmed = trimmed.substr(0, 8);
}
let numbers = [];
for (let i = 0; i < trimmed.length; i += 2) {
numbers.push(trimmed.substr(i, 2));
}
input.value = numbers.join('-');
}
}
this is what i am getting
my expected result is i.e 08-17-2019
can anyone help me how can i achieve that?
Modified your directive a little bit and its working fine
import {Directive,HostListener} from '@angular/core'
@Directive({
selector: '[dobMask]'
})
export class DobDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
let trimmed = input.value.replace(/\s+/g, '');
if (trimmed.length > 10) {
trimmed = trimmed.substr(0, 10);
}
trimmed = trimmed.replace(/-/g,'');
let numbers = [];
numbers.push(trimmed.substr(0,2));
if(trimmed.substr(2,2)!=="")
numbers.push(trimmed.substr(2,2));
if(trimmed.substr(4,4)!="")
numbers.push(trimmed.substr(4,4));
input.value = numbers.join('-');
}
}
First issue was you were trimming with length 8 , it should be 10 (including '-')
Then for loop your were always increment 2 , that will not work out as we require 4 values in last item.
Also you need to remove '-' before further you proceed with your logic.
check this