The AppComponent acts as the root component, importing essential modules and components like
RouterOutlet
, ReactiveFormsModule
, CardFormComponent
, and the
NgxMaskDirective
. It renders the <app-card-form>
component within the container.
This component is responsible for rendering form inputs with labels and validation error messages.
It takes in two @Input()
properties: control (which binds to a FormControl
) and
label.
Validation errors are handled via the showErrors()
method, which checks if the input has been touched and
contains errors, displaying the appropriate error messages for required, minlength,
maxlength, and pattern validation rules.
The CardFormComponent is the main form handling component, encapsulating the form fields like Name, Card
Number, Expiration, and Security Code. It uses the ReactiveFormsModule
to handle form state and validation.
Each field in the form is bound to its own FormControl
with specific validators:
- Name: required, minLength(3), maxLength(30)
- Card Number: required, minLength(16), maxLength(16)
- Expiration: required, custom validation using
DateFormControl
, pattern for MM/YY format - Security Code: required, pattern for a 3-digit numeric code
The form includes two buttons:
- Submit: Enabled only if the form is valid, it logs the form submission to the console.
- Reset: Resets all form controls to null values.
The CardComponent is responsible for displaying the visual representation of the credit card details.
The input values from the cardForm
fields (name, card number, expiration) are passed to it using
@Input()
bindings.
This is a custom form control extending Angular's FormControl
class to handle formatting for the expiration
date. It includes:
- Automatic insertion of a forward slash (/) after the second character for MM/YY format.
- Prevents invalid characters and restricts input to a maximum of 5 characters.
- Reactive Forms with Validation: The project uses Angular’s reactive forms, allowing powerful form validation and dynamic input handling.
- Masked Input: The
NgxMaskDirective
is integrated to ensure proper formatting for inputs like card number and expiration. - Custom Form Control: The
DateFormControl
demonstrates how to extendFormControl
for specific input behaviors like formatting a date string. - Dynamic Input Handling: The form is flexible, with the card information dynamically updated in the preview component as users fill out the form.
- Error Handling: Validation errors are displayed inline, with specific error messages based on the type of validation failure.