Search code examples
angulartypescriptangular2-formbuilder

validate E-mail with white space with regular expression with angular form-builders


I am using the form builders to validate the E-mail,

TS:

this.registerForm = this.formBuilder.group({
      userName: [
        '',
        [
          Validators.required,
          Validators.email,
          Validators.pattern(
            '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$'
          ),
        ],
      ],
    });
  }

get f() {
    return this.registerForm.controls;
  }

validateEmail() {
    this.submitted = true;
    if (this.registerForm.invalid) {
      console.log('Invalid');
      return;
    }
    console.log(this.registerForm.value.userName + ' is a valid Email');
  }

HTML

<form [formGroup]="registerForm" (ngSubmit)="validateEmail()">
  <input
    [ngClass]="{
      'is-invalid': submitted && f.userName.errors,
      blueLine: submitted && f.userName.errors
    }"
    type="text"
    formControlName="userName"
  />
  <button (click)="validateEmail()">Validate</button>
</form>

There is a requirement that user may enter few white spaces at the end of the E-mail id , how to trim the white spaces at the end of the E-mail before validating the E-mail.

eg:

"someone.someone.com " // used 3 white spaces after .com this should trim all the white spaces after .com

stackblitz link : you can check the code implementation here


Solution

  • First, you need to remove the Validators.email in your validators to allow white spaces in your form control. Next, you need to create a custom validator that will trim the end of the control value first before checking the regex pattern. Then, add the custom validator as one of your validators.

    I modified the stackblitz you created and added my solution.

    import {
      Component,
      OnInit,
      VERSION
    } from '@angular/core';
    import {
      FormBuilder,
      FormControl,
      FormGroup,
      Validators,
    } from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements OnInit {
      name = 'Angular ' + VERSION.major;
      email: string;
      registerForm: FormGroup;
      submitted: boolean;
    
      //Constructor
      constructor(private formBuilder: FormBuilder) {}
    
      // On init function
      ngOnInit() {
        this.submitted = false;
        this.registerForm = this.formBuilder.group({
          userName: ['', [Validators.required, emailWithWhitespaceValidator]],
        });
      }
      get f() {
        return this.registerForm.controls;
      }
    
      validateEmail() {
        this.submitted = true;
        if (this.registerForm.invalid) {
          console.log('Invalid');
          return;
        }
        console.log(this.registerForm.value.userName + ' is a valid Email');
      }
    }
    
    export function emailWithWhitespaceValidator(control: FormControl) {
      const isValid = control.value
        .trimEnd()
        .match('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$');
      return isValid ? null : {
        isValid: false
      };
    }