[Angular] Using directive to create a simple Credit card validator
2024-08-28 15:12:16
We will use 'HostListener' and 'HostBinding' to accomplish the task.
The HTML:
<label>
Credit Card Number
<input
name="credit-card"
type="text"
credit-card
placeholder="Enter your 16-digit card number">
</label>
Create directive:
import { Directive, ElementRef, HostListener, HostBinding } from '@angular/core'; @Directive({
selector: '[credit-card]'
})
export class CreditCardDirective {
constructor(private element: ElementRef) {}
}
Add a HostListener when user type input:
And we want that the max length of string user type is 16 and it should be formatted as '6666 6666 6666 6666'.
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
this.border = "";
const input = event.target as HTMLInputElement; // the length should be no more than 16
let trimmed = input.value.replace(/\s+/g, '');
if(trimmed.length > 16) {
trimmed = trimmed.substr(0, 16);
} // should be 6666 6666 6666 6666
let numbers = [];
for(let i = 0; i < trimmed.length; i +=4) {
numbers.push(trimmed.substr(i, 4));
} input.value = numbers.join(' ');
}
Now we want to use @HostBinding to change style props when what user entered is not a number:
onKeyDown(event: KeyboardEvent) {
this.border = "";
const input = event.target as HTMLInputElement; // the length should be no more than 16
let trimmed = input.value.replace(/\s+/g, '');
if(trimmed.length > 16) {
trimmed = trimmed.substr(0, 16);
} // if we pass in char, show red border
if((/[^\d]/g).test(trimmed)) {
this.border = '1px solid red';
} // should be 6666 6666 6666 6666
let numbers = [];
for(let i = 0; i < trimmed.length; i +=4) {
numbers.push(trimmed.substr(i, 4));
} input.value = numbers.join(' ');
}
最新文章
- WHMCS成功安装和使用方法及添加支付宝,PayPal收款教程
- Moon.Orm 5.0(MQL版)及之前版本的开源计划
- JavaScript DOM学习总结(一)
- ThinkPHP中getField( )和field( )
- 【转】Tomcat中部署java web应用程序
- Masonry 固定宽度 等间距
- 获取scrollTop兼容各浏览器的方法,以及body和documentElement
- Coreseek:索引和检测的第二步骤施工
- 每天一个Linux命令(11)--nl命令
- WPF 自定义RadioButton样式
- javascript 正则表达式补充
- UOJ236 IOI2016 Railroad 差分、欧拉回路、最小生成树
- Oracle 存储过程或函数传入的数值参数number
- 阿里云服务器搭建FTP
- Django MTV模式详解
- 2017广东工业大学程序设计竞赛决赛 Problem E: 倒水(Water) (详解)
- LOJ121 【离线可过】动态图连通性
- Vue学习笔记:编译过程
- Vuex-Action
- Mac上Homebrew的使用——Homebrew 使 OS X 更完整
热门文章
- 【Codeforces Round #452 (Div. 2) D】Shovel Sale
- 课程与教学管理系统(CMS):Sakai
- [appium]-9宫格解锁方法
- 详解javascript的深拷贝与浅拷贝
- Visual C# 2008 调试技巧
- UML学习总结(3)——StarUML指导手册
- Maven报错Missing artifact jdk.tools:jdk.tools:jar:1.7--转
- [Node] Run Any Version of a Node Tool with npx
- js实现类似页面广告一段时间自动打开一段时间自动关闭的功能
- [Angular2] @Ngrx/store and @Ngrx/effects learning note