Utilizing Angular Validators.email with the ability to accept null values

In my .ts file, I have an Angular validator set up like this:

this.detailsForm = formBuilder.group(
{
    email: ['', Validators.compose([Validators.email])]
});

While this setup works fine, the email validator also applies the required validation. I actually want to allow a null value as well. Is there a way to achieve this?

Answer №1

The reason is simply that a null or empty value will not match the expected shape (regexp).

To see the current regular expression used with Validators.email, check out this link:

const EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;

console.log(EMAIL_REGEXP.test('')); // false
console.log(EMAIL_REGEXP.test(null)); // false
console.log(EMAIL_REGEXP.test('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f796b796d994989a">[email protected]</a>')); // true

If you want to achieve this functionality, you can either create a custom validator that accepts this Regexp or a null/empty value, or consider using an async validator like I would in this case. Check out more information on creating asynchronous validators here.

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

Typescript is missing Zod and tRPC types throughout all projects in the monorepo, leading to the use of 'any'

Recently, I've found myself stuck in a puzzling predicament. For the last couple of weeks, I've been trying to troubleshoot why the types are getting lost within my projects housed in a monorepo. Even though my backend exposes the necessary types ...

How to efficiently schedule a series of delayed local notifications in Ionic 2

I keep receiving notifications for the second object but not the first. I am utilizing the Local Notifications plugin from ionic native, which you can find more information about here: https://ionicframework.com/docs/v2/native/local-notifications/. Any a ...

What is the best way to get my Discord bot to respond in "Embed" format using TypeScript?

I've been attempting to create a bot that responds with an embedded message when mentioned, but I'm running into some issues. Whenever I run this code snippet, it throws an error in my terminal and doesn't seem to do anything: client.on(&apo ...

In Typescript, issues arise when trying to assign types with inheritance in Generics - Type mismatch detected

As I work on creating a generic parent class to handle multiple children, I have encountered a challenge. My goal is to define an abstract function in the parent class that will take in a child object and return that same class. Here's my initial atte ...

How to use Angular i18 for localizing the value of an interpolated string in a

In my Angular application, I have two translations in xliff format. The first one is @@field-is-required, which includes a string interpolation, and the second one is @@lastname, a regular translation. <trans-unit id="field-is-required" dataty ...

Prevent toggle button from activating panel expansion

Is there a way to add toggle buttons to the description section of an expansion panel without triggering the expansion panel when interacting with the buttons? I have included an example here. ...

Creating an observer for a multiple selection dropdown in Aurelia: step by step tutorial

In my current setup, I have a dropdown menu that allows users to select a single option. This selection automatically provides me with the filtering value as an observable. Here is how it works: public months: any=[]; @observable public selectedMonth: ...

Issue with Angular 6: Struggling to Implement DatePipe

I am trying to set the current date within a formGroup in a specific format, but I keep encountering an error with the code below: 'Unable to convert "13/07/2020" into a date' for pipe 'DatePipe' this.fb.group({ startdateActivi ...

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

How can I store an array of objects in a Couchbase database for a specific item without compromising the existing data?

Here is an example: { id:1, name:john, role:[ {name:boss, type:xyz}, {name:waiter, type:abc} ] } I am looking to append an array of objects to the existing "role" field without losing any other data. The new data should be added as individual ob ...

Issue encountered: Jest-dom is throwing a TypeError because $toString is not recognized as a function on a project using Typescript, React

I have been facing a challenge while setting up jest and @testing-library/jest-dom for my typescript/react/next.js website. Each time I try running the tests, an error occurs, and I am struggling to identify the root cause. This issue has been perplexing ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...

What is the best way to clear all content from the "textarea" and input fields after submitting?

I'm currently using a Devextreme library for my project. I am having trouble finding a way to clear all the textarea information in the component along with other inputs when clicking on the Save button. Despite trying various methods, I have not bee ...

Integrating mat-table within mat-expansion panel in an Angular 10 application

I am trying to create a list of users with an expandable addresses table when each user is clicked. However, for some reason, the expanded table appears blank. Can anyone help me figure out what the issue might be? You can view the code here: Stackblitz ...

Issue: The login.component.html file failed to load

I attempted to utilize a custom-made HTML file with the templateUrl attribute in Angular2. Below is the content of my login.component.ts file: import {Component} from '@angular/core'; @Component({ selector: 'login' , template ...

Having trouble integrating NEXT AUTH with Firebase due to an error: "Cannot import statement outside

Let's take a look at our firebase configuration file: import { getFirestore } from "firebase/firestore"; export const firebaseConfig = { apiKey: process.env.FIREBASE_API_KEY, authDomain: process.env.FIREBASE_AUTH_DOMAIN, projectId: pr ...

Steps for generating a multer file using a link to an image

My current challenge involves downloading an image from a public URL, converting it into a multer file format, and then uploading it using an existing API. So far, I've experimented with axios using responseType: "blob" and responseType: "arraybuffer" ...

An issue has occurred: Failure to execute spawnSync PATH/target/node/node ENOENTNGCC. Please refer to the

Attempting to initiate my angular project using ./mvnw is resulting in an error when the build runs ng build --configuration development. The error message thrown reads as follows: Generating browser application bundles (phase: setup)... [INFO] /home/use ...

Beware: React higher-order component alert - Caution: It is not possible to modify a component from within the function body of another

Recently, I crafted a simple higher-order component that retrieves data from an API endpoint and handles loading, error messages, or displaying content upon success. Although the component functions correctly, it triggers the following error message: War ...

Ways to receive one of two variations

Dealing with different cases for type is my current challenge. In a React Functional Component, I have a callback function property that accepts an argument of either string or number. interface InputProps { getValue?: (value: string | number) => vo ...