zoukankan      html  css  js  c++  java
  • [Angular] Using directive to create a simple Credit card validator

    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(' ');
      }
  • 相关阅读:
    canvas beginPath()的初步理解
    高效取余运算(n-1)&hash原理探讨
    EntityUtils.toString(entity)处理字符集问题解决
    python计算不规则图形面积算法
    VMware与 Device/Credential Guard 不兼容,解决办法及心得
    Java爬取51job保存到MySQL并进行分析
    纯C语言实现循环双向链表创建,插入和删除
    纯C语言实现顺序队列
    纯C语言实现链队
    纯C语言实现链栈
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6522464.html
Copyright © 2011-2022 走看看