To create a credit card input field in an Angular component form with validation and formatting, you can follow a structured approach using Angular Reactive Forms and optionally some helper libraries or custom directives. Below is a comprehensive guide based on best practices and available tools:
1. Set Up Angular Reactive Form
First, create a reactive form in your Angular component that includes a credit card number field.
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-credit-card-form',
templateUrl: './credit-card-form.component.html'
})
export class CreditCardFormComponent implements OnInit {
creditCardForm: FormGroup;
ngOnInit() {
this.creditCardForm = new FormGroup({
cardNumber: new FormControl('', [
Validators.required,
Validators.pattern(/^\d{13,19}$/) // Basic pattern for card number length
])
});
}
onSubmit() {
if (this.creditCardForm.valid) {
console.log('Credit Card Number:', this.creditCardForm.value.cardNumber);
}
}
}
2. Create the Template with Input Field and Validation Messages
<form (ngsubmit)="onSubmit()" [formgroup]="creditCardForm">
<label for="cardNumber">Credit Card Number</label>
<input (input)="formatCardNumber()" formcontrolname="cardNumber" id="cardNumber" placeholder="Enter your credit card number" type="text"/>
<div *ngif="creditCardForm.get('cardNumber').invalid && creditCardForm.get('cardNumber').touched">
<small *ngif="creditCardForm.get('cardNumber').errors.required">Card number is required.</small>
<small *ngif="creditCardForm.get('cardNumber').errors.pattern">Invalid card number format.</small>
</div>
<button [disabled]="creditCardForm.invalid" type="submit">Submit</button>
</form>
3. Optional: Format Credit Card Number with Spaces
To improve UX, format the card number as the user types (e.g., add spaces every 4 digits). You can implement this in the component:
formatCardNumber() {
let input = this.creditCardForm.get('cardNumber').value.replace(/\D/g, ''); // Remove non-digits
// Format as groups of 4 digits
let formatted = input.match(/.{1,4}/g)?.join(' ') || '';
this.creditCardForm.get('cardNumber').setValue(formatted, { emitEvent: false });
}
This keeps the input readable while maintaining the form control value.
4. Advanced Validation: Luhn Algorithm
For more robust validation, implement the Luhn algorithm as a custom validator:
import { AbstractControl, ValidationErrors } from '@angular/forms';
export function luhnValidator(control: AbstractControl): ValidationErrors | null {
const value = control.value.replace(/\s+/g, '');
if (!value) return null;
let sum = 0;
let shouldDouble = false;
for (let i = value.length - 1; i >= 0; i--) {
let digit = parseInt(value.charAt(i), 10);
if (shouldDouble) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
shouldDouble = !shouldDouble;
}
return sum % 10 === 0 ? null : { luhnInvalid: true };
}
Add this validator to your form control:
this.creditCardForm = new FormGroup({
cardNumber: new FormControl('', [
Validators.required,
Validators.pattern(/^\d{13,19}$/),
luhnValidator
])
});
And display the error in the template:
<small *ngif="creditCardForm.get('cardNumber').errors.luhnInvalid">Invalid credit card number.</small>
5. Using Angular Libraries for Credit Card Input (Optional)
You can also use existing Angular directives like angular-credit-cards which provide parsing, validation, and card type detection out of the box:
npm install angular-credit-cards
import { CreditCardsModule } from 'angular-credit-cards';
@NgModule({
imports: [
// other imports
CreditCardsModule
]
})
export class AppModule {}
<form name="paymentForm">
<input cc-eager-type="" cc-number="" name="cardNumber" ng-model="card.number" type="text"/>
<p ng-show="paymentForm.cardNumber.$invalid && paymentForm.cardNumber.$ccEagerType">
Looks like you're typing a {{paymentForm.cardNumber.$ccEagerType}} number!
</p>
<p ng-show="paymentForm.cardNumber.$valid">
Yes, that looks like a valid {{paymentForm.cardNumber.$ccType}} number!
</p>
</form>
This library handles validation and card type detection automatically[1].
Summary
- Use Angular Reactive Forms to create a credit card input field.
- Add basic validation with required and pattern validators.
- Format input for better UX by inserting spaces.
- Implement Luhn algorithm as a custom validator for card number validity.
- Optionally, use libraries like
angular-credit-cards for advanced features like card type detection and validation.
This approach ensures a robust, user-friendly credit card input field in your Angular component form.