coder
coder

Reputation: 99

validation of input mask in FromGroup

I got example of credit card FormGroup, using Angular directive, I created input mask for input 4444444444444444 became 4444 4444 4444 4444, but the problem is I got regex validation which do not accept space. this is what I had tried,

ts.file

  {
    this.creditCardForm = builder.group({
      creditCardNumber: ['', [creditCardNumberValidators]]
    });

  }   
}

function creditCardNumberValidators(c: FormControl) {
  const isVisa = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;

  return isVisa.test(c.value)
    ? null
    : {
        validateInput: {
          valid: false,
        },
      };
}



@Directive({
  selector: '[creditCardMask]',
})
export class CreditCardMaskDirective {
  @HostListener('input', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;

    let trimmed = input.value.replace(/\s+/g, '');
    if (trimmed.length > 16) {
      trimmed = trimmed.substr(0, 16);
    }

    const numbers = [];
    for (let i = 0; i < trimmed.length; i += 4) {
      numbers.push(trimmed.substr(i, 4));
    }

    input.value = numbers.join(' ');
  }
}

and this is my stackblitz demo, based on my finding I can have 2 solutions:

need suggestion and if there are better practice to solve this, thanks

Upvotes: 1

Views: 1258

Answers (1)

Nikhil
Nikhil

Reputation: 6643

Use the same regex you are using but remove spaces from card number before validating.

You can use String.split() and Array.join() to do that.

function creditCardNumberValidators(c: FormControl) {
  const isVisa = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;

  // Remove spaces.
  let cardNumber = c.value.trim().split(' ').join('');

  return isVisa.test(cardNumber)
    ? null
    : {
        validateInput: {
          valid: false,
        },
      };
}

String.replace() can also be used to remove spaces.

let cardNumber = c.value.replace(/\s/g, '');

Live demo on StackBlitz: https://stackblitz.com/edit/angular-reactive-forms-12jq6d

Upvotes: 1

Related Questions