Javascript 掩码输入值日期格式
我想屏蔽我的Javascript 掩码输入值日期格式,javascript,angular,typescript,masking,Javascript,Angular,Typescript,Masking,我想屏蔽我的输入值,基本上我有一个用于信用卡到期日期的输入字段,并想以mm/yy格式屏蔽它,这是我尝试过的: 输入掩码指令.ts import { Directive, HostListener } from '@angular/core'; import { NgControl } from '@angular/forms'; @Directive({ selector: '[formControlName][appInputMask]', }) export class InputMa
输入
值,基本上我有一个用于信用卡到期日期的输入字段,并想以mm/yy
格式屏蔽它,这是我尝试过的:
输入掩码指令.ts
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, 4);
if (trimmed.length > 3) {
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2)}`);
}
}
}
我得到了预期的输出,但问题是当在输入字段上使用退格时,它搞砸了,这是我的演示,如何解决这个问题?或者在输入掩码上有更好的方法吗?只需给出日期、卡片等的图案,就可以使您的工作变得简单
这就是问题所在
const trimmed=input.value.replace(/\s+/g').slice(0,4)中代码>如果它包含斜杠,则切片的结尾应该是5,而不是4
return
语句中
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2)}`);
${trimmed.slice(2)
将返回/\d{1,2}
。因此需要避免斜杠,从3开始
解决方案
将“最大长度”从4更改为5
<input ... maxlength="5">
到
因为当您添加/
时,长度将变为5
不要使用.slice(0)
,因为它允许用户粘贴5位数字,当您添加斜杠时,它将变成6位。因此日期将看起来像11/111
,而不是11/11
改变
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2)}`);
到
这就是你的代码被弄乱的地方。如果它包含一个斜杠,那么你应该从3中切掉它。否则从2中切掉它
输入掩码指令中HostListener的最终代码
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
const trimmed = input.value.replace(/\s+/g, '').slice(0, input.value.indexOf('/')==-1?4:5);
if (trimmed.length > 3) {
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(trimmed.indexOf('/')==-1?2:3)}`);
}
}
工作示例:good library,有没有使用指令作为我的问题的解决方案?这不会过滤月份。例如,如果输入888,输出为88/88I,但不包括特殊字符,这就是为什么我添加
maxLength=4
,这不会过滤月份。例如,如果输入8888,输出为88/88I,请共享e月过滤器的工作示例。
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2)}`);
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(trimmed.indexOf('/')==-1?2:3)}`);
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
const trimmed = input.value.replace(/\s+/g, '').slice(0, input.value.indexOf('/')==-1?4:5);
if (trimmed.length > 3) {
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(trimmed.indexOf('/')==-1?2:3)}`);
}
}