Check the validity of an email address that contains white space using a regular expression within angular form-builders

I'm currently utilizing form builders for E-mail validation.

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>

A scenario requires allowing users to input white spaces at the end of an E-mail address. How can these trailing white spaces be removed before validating the E-mail?

Example:

"someone.someone.com " // 3 white spaces after .com should be trimmed

Check out the code implementation on StackBlitz.

Answer №1

To allow white spaces in your form control, remove the Validators.email from your validators. Additionally, create a custom validator that trims the end of the control value before checking the regex pattern. Finally, include the custom validator among your validators.

I have enhanced the StackBlitz example you provided by implementing 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
  };
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the "Unrecognized teardown 1" error when subscribing to an Observable in Typescript and Angular2

Having trouble with using an Observable in my Angular2.rc.4 Typescript app. Check out the plunker for it here: https://embed.plnkr.co/UjcdCmN6hSkdKt27ezyI/ The issue revolves around a service that contains this code: private messageSender : Observable< ...

Show a Toast in React without relying on useEffect to manage the state

I have successfully implemented the Toast functionality from react-bootstrap into my application using the provided code. However, I am unsure if it is necessary to utilize useEffect to set show with setShow(items.length > 0);. Would it be simpler to ...

What is the specific event type triggered by the onError event when utilizing an img tag?

I'm attempting to display an image. If the URL fails to load, I want to show a different image instead. Currently, my code is functioning properly, but I am utilizing type "any" for the event. What should be the appropriate type for the event? functi ...

Template containing an observable collection of observables

Since the title is not helping me achieve my goal, let me explain what I'm trying to accomplish. My objective is to show a list of items in the view, which are fetched asynchronously from the backend. The service I have has a method called fetchItems ...

"Error occurs as a result of an unspecified attribute in the map

Hello, I am currently traversing a tree structure recursively. To handle undefined nodes in the tree, I have implemented guards to prevent any failures. However, during the mapping of children nodes, I encountered the following error: Error Output Adri ...

Establish a connection between an Angular client and a Spring backend using JWT for authentication

I successfully integrated JWT into my Spring backend by following the steps outlined in this informative guide: https://auth0.com/blog/securing-spring-boot-with-jwts/ Interestingly, when I perform a PUT request using Postman, everything seems to be workin ...

HTML not rendering Angular object as expected

Having trouble with my Angular project on LinkedInLearning. Can't seem to display object properties in my component, even though I can see them when logging the object. The boolean value renders fine, but not the object properties. Here is the snippe ...

How to use RxJs BehaviorSubject in an Angular Interceptor to receive incoming data

Being a newcomer to rxjs, I grasp most operators except for the specific use case involving BehaviorSubject, filter, and take. I am working on renewing an oauth access and refresh token pair within an Angular interceptor. While reviewing various codes fro ...

Encountering a Zone.js error when trying to load an Angular 7 app using ng serve, preventing the application from loading

Scenario: Yesterday, I decided to upgrade my Angular app from version 5.2.9 to 6 and thought it would be a good idea to go all the way to 7 while I was at it. It ended up taking the whole day and required numerous changes to multiple files, mostly due to R ...

Angular 2 component downgrade issue: What causes the error when constructor parameters are involved? (SystemJS) Unable to resolve all parameters for (?)

Consider this line as an example: constructor(private elementRef: ElementRef, private zone: NgZone) {} In order for the downgrade to be successful without any errors, I must remove the parameters from the constructor. Otherwise, I encounter the follo ...

Tips for implementing data-autoload, data-origin, and data-callback script tags in Angular with typescript

I am facing an issue while trying to insert my script into an Angular application using the 'data-autoload', 'data-origin', and 'data-callback' keys. When I attempted to create the script element using '_renderer2.createE ...

Guide to automatically blur the input field and toggle it upon clicking the checkbox using Angular

<input (click)="check()" class="checkbox" type="checkbox"> <input [(ngModel)]="second_month" value="2019-09" type="month" [class.blurred]="isBlurred">> I need the second input(type=month) field to be initially blurred, and only unblur ...

Executing functions on React components with no render method

Currently, I am in need of a component that will handle app settings. This particular component, named Settings, utilizes the useState() hook to store state values such as the primary color scheme. I aim to have a single instance of this Settings componen ...

What are the mechanisms involved in the change detection process of Angular 2?

When it comes to change detection in Angular 1, the method used is dirty checking of the $scope hierarchy. It involved creating watchers either implicitly or explicitly in templates, controllers, or components. Angular 2, on the other hand, no longer reli ...

Exploring the Features of PrimeNG Table Component in Angular 8

After attempting to implement p-table (PrimeNG table) in my Angular project and importing all necessary dependencies and modules using the CLI, I encountered the following error: ERROR: The target entry-point "primeng/table" has missing dependencies: - @ ...

Steer clear of mentioning unbound methods, as they can lead to accidental scoping errors with 'this' when invoking static methods

I've been working on a method map based on a query from the Stack Overflow post linked here to assist me in dynamically calling a static method. But, I keep encountering this error message: Avoid referencing unbound methods that could lead to uninte ...

Unlocking the union of elements within a diverse array of objects

I have an array of fields that contain various types of input to be displayed on the user interface. const fields = [ { id: 'textInput_1', fieldType: 'text', }, { id: 'selectInput_1', fieldType: 'sel ...

Utilizing WebPack 5 in conjunction with Web workers in a React/Typescript environment

Can someone help me figure out how to make a web worker function properly with create-react-app, Typescript, and Webpack 5? I've been struggling with limited documentation and can't seem to find a clear explanation. I'm trying to avoid using ...

Tips for retrieving the angular route parameters from the URL?

I'm working with an Angular route that looks like this: /Chapter/:chapterId/Section/:sectionId. Let's say I have a URL such as: http://server.com/Chapter/1/Section/2?search=moby. Is there a way to extract the parameters and query string in Angu ...

Ways to access information from an Angular model within a controller

hydrate.component.ts import { Component } from 'angular/core'; import { userDataService } from 'some/different/path'; @Component({ selector: 'hydrate', templateUrl: './hydrate.component.html' ...