Search⌘ K
AI Features

Validating the Other Inputs

Explore how to validate different inputs in Angular reactive forms by applying built-in validators like required, minlength, maxlength, and regex patterns. Understand ensuring correct formats for credit card number, expiration date, and CVV while adding user-friendly error messages for validation feedback.

Let’s validate the other inputs in the form. We’re going to introduce new validators. This means that we’ll have to add additional messages as well. Let’s get started.

Validators

We’ll be modifying the configuration object for the form group we created in the app.component.ts file. We’ll update it to the following:

TypeScript 3.3.4
export class AppComponent {
ccForm = new FormGroup({
name: new FormControl('', [
Validators.required,
Validators.minLength(3)
]),
num: new FormControl('', [
Validators.required,
Validators.minLength(16),
Validators.maxLength(16)
]),
expiration: new FormControl('', [
Validators.required,
Validators.pattern(/^(0[1-9]|1[0-2])\/\d{2}$/)
]),
cvv: new FormControl('', [
Validators.required,
Validators.minLength(3),
Validators.maxLength(3)
])
});
submit() {
console.log('form submitted');
}
}

We’re making a lot of changes here. Let’s run through each form control’s validators one by one.

num

The num form control refers to the credit card number. We’re making it a required value using Validators.required. This will go for all other fields as well. We’re also checking its minimum and maximum length using the Validators.minLength and ...