Creating a Credit Card Input Field in an Angular Component Form
To create a robust credit card input field in an Angular component form, you need to combine form controls, validation (including Luhn's algorithm), and user-friendly formatting. Below is a step-by-step guide for a modern Angular (2+) application using Reactive Forms.
1. Set Up the Reactive Form
First, import the necessary modules in your component:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl, ValidationErrors } from '@angular/forms';
2. Implement the Luhn Validator
Create a custom validator for credit card numbers using Luhn's algorithm:
function luhnValidator(control: AbstractControl): ValidationErrors | null {
const value = (control.value || '').replace(/\D/g, '');
let sum = 0;
let shouldDouble = false;
for (let i = value.length - 1; i >= 0; i--) {
let digit = +value[i];
if (shouldDouble) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
shouldDouble = !shouldDouble;
}
return sum % 10 === 0 ? null : { luhnInvalid: true };
}
This validator checks if the input is a valid credit card number[8][4].
3. Create the Form Group
Set up your form group in the component:
@Component({
selector: 'app-credit-card-form',
templateUrl: './credit-card-form.component.html'
})
export class CreditCardFormComponent {
cardForm: FormGroup;
constructor(private fb: FormBuilder) {
this.cardForm = this.fb.group({
cardNumber: ['', [Validators.required, luhnValidator]],
expiry: ['', [Validators.required, Validators.pattern('(0[1-9]|1[0-2])\/?([0-9]{2})')]],
cvc: ['', [Validators.required, Validators.pattern('^[0-9]{3,4}$')]]
});
}
}
4. Build the Template
Use Angular's form controls and display validation errors:
<form (ngsubmit)="onSubmit()" [formgroup]="cardForm">
<label>
Card Number
<input (input)="formatCardNumber($event)" formcontrolname="cardNumber" maxlength="19" placeholder="1234 [CREDIT_CARD_NUMBER]" type="text"/>
</label>
<div *ngif="cardForm.get('cardNumber').hasError('required') && cardForm.get('cardNumber').touched">
Card number is required.
</div>
<div *ngif="cardForm.get('cardNumber').hasError('luhnInvalid') && cardForm.get('cardNumber').touched">
Invalid card number.
</div>
<label>
Expiry (MM/YY)
<input formcontrolname="expiry" maxlength="5" placeholder="MM/YY" type="text"/>
</label>
<div *ngif="cardForm.get('expiry').hasError('required') && cardForm.get('expiry').touched">
Expiry date is required.
</div>
<div *ngif="cardForm.get('expiry').hasError('pattern') && cardForm.get('expiry').touched">
Invalid expiry format.
</div>
<label>
CVC
<input formcontrolname="cvc" maxlength="4" placeholder="CVC" type="text"/>
</label>
<div *ngif="cardForm.get('cvc').hasError('required') && cardForm.get('cvc').touched">
CVC is required.
</div>
<div *ngif="cardForm.get('cvc').hasError('pattern') && cardForm.get('cvc').touched">
Invalid CVC.
</div>
<button [disabled]="cardForm.invalid" type="submit">Submit</button>
</form>
5. Format Card Number Input
Optionally, format the card number as the user types (e.g., with spaces every 4 digits):
formatCardNumber(event: any) {
let input = event.target.value.replace(/\D/g, '').substring(0, 16);
let sections = [];
for (let i = 0; i < input.length; i += 4) {
sections.push(input.substring(i, i + 4));
}
event.target.value = sections.join(' ');
this.cardForm.get('cardNumber').setValue(event.target.value, { emitEvent: false });
}
This improves UX and matches common card input formatting[2][4].
Summary Table
| Field | Validators | Example Input | Notes |
|---|
| Card Number | Required, Luhn (custom) | [CREDIT_CARD_NUMBER] | Spaces auto-inserted |
| Expiry | Required, Pattern (MM/YY) | 12/25 | Regex for MM/YY |
| CVC | Required, Pattern (3 or 4 digits) | 123 | 4 digits for Amex |
Alternatives and Enhancements
- Use a library: Packages like
ng-payment-card or angular-credit-cards provide ready-made components and directives for credit card forms, including validation and formatting[1][9][10].
- Card type detection: You can enhance the UX by detecting and displaying the card type as the user types[6][7].
- Expiration and CVC validation: Adjust CVC length and expiry validation based on detected card type[6].
This approach gives you a reusable, validated credit card input field in Angular, suitable for integration into any payment or checkout form[6][8].