Ways to validate email input with pattern in Angular 2

I need help figuring out how to use the email pattern error for validation using the hasError function in Angular 2. My goal is to apply the invalid class to my input field. Below, you can see the code from registration.component.html:

<div class="input-field col s6">
    <input id="Email" type="email" [formControl]="myCustomForm.controls['email']" [ngClass]="{invalid: myCustomForm.controls['email'].touched && myCustomForm.controls['email'].hasError('required')}">
    <label for="Email">Email</label>
</div>

And here's the code snippet from registration.component.ts:

constructor(private fb: FormBuilder, private ASD: AppStartupData, private af: AngularFire) {
this.registration_id;
this.svc_AppStartupData = ASD;
this.myCustomForm = fb.group({
  "first_name": ['', Validators.required],
  "middle_name": [''],
  "last_name": ['', Validators.required],
  "gender": ['', Validators.required],
  "email": ['', Validators.compose([Validators.required, Validators.pattern("^[a-zA-Z0–9_.+\\-\\]+@[a-zA-Z0–9-]+.[a-zA-Z0–9\\-\\.]+$")])],
  "password": ['', Validators.required],
  "telephone": ['', Validators.required],
  "cities": ['', Validators.required],
  "address": ['', Validators.required],
  "dob": ['', Validators.required]
});
}

Answer №1

After conducting some research on validating email controls in Angular 2 with the ontouched parameter, I was able to come up with a solution. Below is the code snippet that I implemented within my registration.component.ts file:

customValidation(control: FormControl): { [s: string]: boolean } {
    if (!control.value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
        return { invalidSku: true };
    }
}

Furthermore, I made sure to include the following line in my registration.component.html file:

[ngClass]="{invalid: myCustomForm.controls['email'].touched && myCustomForm.controls['email'].hasError('invalidSku')}"

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

Create dynamic modals in ReactJS that appear when a row is clicked

Engaged in a project for an undisclosed entity where patient data is retrieved from their API and displayed as modal on the page. Clicking on a modal reveals more threat information in another modal. The objective is for these modals to render based on a c ...

Angular 13: Problems arise with custom theme in Angular Material version 13

I've set up a custom theme palette for my project that works perfectly with version ^12.2.13 of Angular Material, but not with ^13.2.3. Here's the SCSS code for my custom theming: my-custom-theme.scss @import '~@angular/material/theming&apo ...

Saving files to MinIO from an Angular2 web form

I am currently working on a prototype for an Angular8 application that is capable of uploading files from a form to MinIO. Below is the structure of the form: upload-form.component.html : <input class="form-control" type="file" (change)="onFileCha ...

Clicking on the Angular custom accordion component does not trigger the expansion feature

I have developed a customized accordion component using Angular 9, but I am encountering an issue. Whenever I click on the accordion, only the first button's window expands while the others remain unaffected. To demonstrate the problem more effective ...

Exploring how to access and read the request body within Angular2

I'm managing a launcher platform for launching various Angular2 applications that I have ownership of, potentially across different domains. I am looking to send configuration details through the request body. Is there a way to send a POST request to ...

The Tauri JS API dialog and notification components are failing to function, resulting in a null return value

Currently, I am getting acquainted with the tauri framework by working on a small desktop application. While testing various tauri JS API modules, most of them have been functioning as expected except for the dialog and notification modules. Whenever I tes ...

Intercepting and manipulating HTTP response headers using Angular's HTTP

After sending a post request for logging in, the response includes a token in the header called Set-Auth. How can I extract and utilize this token in subsequent request headers? login() { if (this.loginForm.invalid) { this.messageService.warnin ...

Tips on how to effectively unit test error scenarios when creating a DOM element using Angular

I designed a feature to insert a canonical tag. Here is the code for the feature: createLinkForCanonicalURL(tagData) { try { if (!tagData) { return; } const link: HTMLLinkElement = this.dom.createElement('link'); ...

Tips for updating the color of checkboxes in an Angular application

I'm looking to update the appearance of a checkbox when it is disabled. app.component.html: <input type="checkbox" class="custom-control-input" [disabled]="item.disabled" [checked]="item.checked"> The cu ...

Creating Instances of Variables Within a Class

Currently, I am working on a project using Ionic and Angular. I have come across various ways of instantiating variables and I'm unsure about the implications of each method. Here are three scenarios that confuse me: export class someClass { myVaria ...

Troubleshooting with matTootip on Safari: Tips for avoiding input-text blockage

I am currently using the matTooltip feature from Angular Material for an input field. However, on Safari, the input field appears to be overlapping, making it impossible to type in. Despite my attempts to change the position of the toolTip, the issue pers ...

What is the reason behind the ineffectiveness of injection in abstraction?

I am working with an interface export interface Tree {} The base class implements this interface: export class TreeBase implements Tree {} There are several concrete classes that extend the TreeBase: export class TreeLayers extends TreeBase {} export cl ...

The traditional function does not have access to a reference to this

For my web development project with Angular 9, I needed to add a typeahead feature using ng bootstrap typeahead. The code provided below worked perfectly: search = (text$: Observable<string>) => text$.pipe( debounceTime(150), disti ...

Refreshing an Angular2 page is triggered by the update of a specific property

Just starting out with Angular2 and I'm puzzled as to why my page keeps refreshing when I try to set some properties from form data. Below is the component snippet: import { Component } from '@angular/core'; import { Credentials } from &ap ...

Tips for incorporating the ternary operator in JSX of a React component while utilizing TypeScript?

I am looking to implement a conditional rendering logic in React and TypeScript, where I need to return null if a specific condition is met, otherwise render a component using a ternary operator. Here is the code snippet I currently have: {condition1 && ...

How to simulate a typescript class using vitest

I am encountering a situation where I have a class A that imports another class B from a separate module and creates an instance of it. While writing tests for class A, I want to stub or mock some of the methods of class B. Below is an example code snippe ...

Using TypeScript along with Nuxt.js and Vuex to access methods from an imported class

Currently, I am in the process of developing a nuxt.js application with typescript and my goal is to segregate the API Calls from the vuex store. However, I've encountered an issue where it seems like I cannot utilize the methods when importing the cl ...

Dealing with consecutive time period inquiries in Angular

My goal is to make 4 consecutive requests in Angular, and for some of these requests, I need to send multiple requests within this.myService.startAudit() until either the timer reaches 30 seconds or we receive a non-empty response. The issue with my curren ...

I'm getting errors from TypeScript when trying to use pnpm - what's going

I've been facing an issue while attempting to transition from yarn to pnpm. I haven't experimented with changing the hoisting settings yet, as I'd prefer not to do so if possible. The problem lies in my lack of understanding about why this m ...

Converted requests from loopback to angular2 resulted in an error message, as the script's MIME type ('text/html') was determined to be non-executable

Currently, I have set up loopback as the backend API and angular2 as the frontend for my project. Loopback is serving my angular2 frontend without any issues. However, whenever I refresh a page, loopback seems to struggle with handling the URL because tha ...