Validating Multiple Email Addresses and Phone Numbers Separated by Commas in Angular Forms
In Angular applications, form validation plays a crucial role in ensuring data integrity and accuracy. Validating a field that accepts multiple email addresses and phone numbers separated by commas can be achieved using Angular’s FormBuilder and Validators.
The Scenario
Let’s consider a scenario where you have a form with a field that accepts a list of email addresses and phone numbers separated by commas. You want to validate this input to ensure that each entry is either a valid email address or a valid phone number.
Implementation Overview
To accomplish this, you can create a custom validation function in your Angular component. This function will parse the input string, split it into individual entries, and then validate each entry against regular expressions for email and phone number formats.
Here’s an example implementation:
import { Component } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss'],
})
export class FormComponent {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
emailsPhones: ['', [Validators.required, this.validateEmailsAndPhones]],
});
}
onSubmit() {
const values = this.myForm.value['emailsPhones'].split(',').map((value) => value.trim());
console.log(values);
// Further processing or submission logic can be performed here
}
validateEmailsAndPhones(control: FormControl) {
const emailsPhonesArray: string[] = control.value.split(',');
const isValid = emailsPhonesArray.every((entry: string) => {
// Email validation using RegExp
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
// Phone number validation using RegExp
const phoneRegex = /^\+?[0-9]\d{1,14}$/;
// Checking if entry is either a valid email or phone number
return emailRegex.test(entry.trim()) || phoneRegex.test(entry.trim());
});
// Returning validation result
return isValid ? null : { invalidEmailsOrPhones: true };
}
}
Understanding the Code
- The
myForm
FormGroup is created with theemailsPhones
FormControl, which uses the custom validation functionvalidateEmailsAndPhones
. - The
validateEmailsAndPhones
function splits the input string into an array of entries, validating each entry against email and phone number regular expressions. - The form displays an error message if any entry fails validation.
Here’s the HTML template associated with the form:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<mat-form-field appearance="outline">
<mat-label>Emails and phones (comma separated)</mat-label>
<input matInput formControlName="emailsPhones" />
@if (myForm.controls['emailsPhones'].hasError('invalidEmailsOrPhones')) {
<mat-error>
Please enter valid phone numbers or email addresses
</mat-error>
}
</mat-form-field>
<button mat-button type="submit" [disabled]="myForm.invalid">
<mat-icon>send</mat-icon>
Submit
</button>
</form>
That can be used to display different scenarios in the view:
- Empty Value:
When the field is left empty, indicating no email or phone entries, the form prompts for required information before allowing submission.
2. Valid Email Address or Phone number:
When a single email address or phone number is valid, the form accepts and confirms it immediately, allowing submission.
3. One valid and One Invalid entry:
When one entry is valid and another is invalid, it indicates an error message.
4. All Entries Valid:
In the case where all email addresses and phone numbers provided are valid, the form confirms their correctness, indicating readiness for submission.
Conclusion
By implementing this approach, you can ensure that your Angular form validates multiple email addresses and phone numbers entered in a comma-separated format, enhancing the user experience and maintaining data accuracy.