Validation of emails in Angular through the utilization of reactive forms

Hello there, I'm new to Angular and looking for some assistance. Specifically, I am currently working on validating an email input using a reactive form with the keyup event.

 registerform:any;
    ngOnInit(): void {
      this.registerform = new FormGroup({
        "emailId": new FormControl(null,[Validators.required,Validators.email])

      });
    }
    get emailid() { return this.registerform.get('emailId');}
<form [formGroup]="registerform" (ngSubmit) = "submitData()">
      <input type="text" formControlName="emailId" placeholder="email">
      <div *ngIf="emailid.invalid && (emailid.touched || emailid.dirty)">
        <span class="myerror" name="err" *ngIf="emailid.errors?.required">*Email is required.</span>
        <span class="myerror" name="err" *ngIf="emailid.errors?.email">*Email is not valid.</span>
      </div>
    </form>

Answer №1

Creating an angular directive is a great alternative to using Validators

@Directive({
selector: '[appEmailValidator]',
providers: [
    { provide: NG_VALIDATORS, useExisting: EmailValidator, multi: true }
    ]
})

export class EmailValidator implements Validator {
    validator: ValidatorFn;
    constructor() {
        this.validator = validateEmailFactory();
    }
    validate(c: FormControl) {
        return this.validator(c);
    }
}



// validation function
function validateEmailFactory(): ValidatorFn {
    return (c: FormControl) => {
        if (c.value) {
            // tslint:disable-next-line:max-line-length
            const isValidEmail = c.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,}))$/);
            const message = {
                emailCheck: {
                    message: 'Email address is invalid'
                }
            };
            return isValidEmail ? null : message;
        }
    };
}

Implement the directive in your input field like this:

<input type="text" id="lpd-email-input" formControlName="email"
              class="form-control"
              [placeholder]="Email address" autocomplete="none" appEmailValidator/>

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

When the promise is resolved, the members of the AngularJS controller are now

I'm experiencing some unexpected behavior in my controller when executing a certain method. The code snippet looks something like this: this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success((StockItems) => { this.StockItems = Stoc ...

Retrieve the input type corresponding to the name and return it as a string using string template literals

type ExtractKeyType<T extends string, K extends number> = `${T}.${K}`; type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends readonly unknown[] ? ExtractKeyType<Key, 0 | 1> : T[Key] extends Record<str ...

Using capital letters with interpolated language keys

The issue: I'm currently facing a problem with i18next. It allows variable interpolation in strings, like "AddNew": "Add new {{item}}". However, I have a language where the grammar requires "{{item}}" to be the first word, as in "AddNew": "{{item}} t ...

Attempting to utilize Array Methods with an Array Union Type

Currently, I am in the process of refactoring an Angular application to enable strict typing. One issue I have encountered is using array methods with an array union type in our LookupService. When attempting to call const lookup = lookupConfig.find(l =&g ...

Discover the subsite inventory of a SharePoint site using TypeScript

Is there a way to gather all sub-sites from my SharePoint site and organize them into a list? I initially thought of using this.context.pageContext, but could not locate it. Please excuse my seemingly simple question, as I am still learning TypeScript. ...

Feeling lost about arrow functions in JavaScript

Here is the code I am currently using to increment the value of intVariable using window.setInterval. var Arrow = (function () { function Arrow() { this.intVariable = 1; this.itemId = -1; this.interval = 25; } Arrow.p ...

What are the best practices for implementing MapLabel in an Angular project?

I need help displaying text on top of multiple polygons on a map. I've heard that Map Label can help with this, but I'm having trouble implementing it and can't find any NPM resources. Here is the Stack Blitz URL for reference: https://stac ...

Error Type: nextjs 13 - children function TypeError

Welcome to the Home page: export default async function Home() { # console.log(data) it is populated const { data } = getAllArts(); return ( <main className="flex min-h-screen flex-col items-center justify-between p-24"> < ...

Encountered an error - 'SyntaxError: unexpected token: ':'' while attempting to load a JSON file for ngx-translate using the Karma test runner

I am currently in the process of setting up system tests for my Angular application. The app utilizes the TranslateModule (ngx-translate) in this manner: TranslateModule.forRoot({ defaultLanguage: 'de', loader: { provide: Tra ...

Exclusive Vue3 Props that cannot be used together

How can a component be created that accepts either json with jsonParserRules or jsonUrl with jsonParserRulesUrl, but not both? It would be ideal if the IDE could provide a warning when both props are specified. Example of an Attempt that does not Work < ...

Guide to automatically have the md-select panel open when the page loads

Utilizing Angular4 along with Redux and angular material to create the layout of my website. In order to accomplish this, I am working on configuring the md-select panel to automatically open. For instance, when a button is clicked, it triggers an action ...

Tips for utilizing generics to determine the data type of a property by its name

I am seeking a method to determine the type of any property within a class or a type. For instance, if I had the classes PersonClass and PersonType, and I wanted to retrieve the type of the nationalId property, I could achieve this using the following cod ...

What Causes mat-bottom-sheet-container to Overflow Instead of Remaining Anchored at the Bottom of the Mobile Screen?

I am encountering an issue with a popup window in my Angular app. Despite testing it on various screen resolutions using Chrome's DevTools Screencast, the popup appears correctly styled and positioned on mobile devices. However, when tested on a real ...

iPhone glitch: When subscribing to an observable, I am immediately shown the initial value it emitted

Could you help me identify the issue in this code? I am attempting to set up data polling, but it seems that the responses after the initial request are not being sent to the back-end. Additionally, all observables return the same value as the first respon ...

Unable to determine all parameters for Angular's DataService

I have been working on developing a versatile service and came across an informative article: https://medium.com/@krishna.acondy/a-generic-http-service-approach-for-angular-applications-a7bd8ff6a068 that guided me in creating my DataService. Here is a snip ...

Does manipulating the context before retrieving it within a custom ContextProvider adhere to best practices?

In my React application, I have a custom ContextProvider component called RepositoryContext. This component requires a specific ID to be set inside it in order to perform CRUD operations. Here is a snippet of the code: import React, { Dispatch, PropsWithCh ...

Tracking mouse movement: calculating mouse coordinates in relation to parent element

I am facing an issue with a mousemove event listener that I have set up for a div. The purpose of this listener is to track the offset between the mouse and the top of the div using event.layerY. Within this main div, there is another nested div. The prob ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

Where is the best location to store types/interfaces so that they can be accessed globally throughout the codebase?

I often find myself wondering about the best place to store types and interfaces related to a specific class in TypeScript. There are numerous of them used throughout the code base, and I would rather not constantly import them but have them available gl ...

Two tags attached to four hypertext links

Within my HTML code, I have hyperlinks present on every line. However, I am seeking to eliminate these hyperlinks specifically from "your previous balance" and "your new balance".https://i.sstatic.net/ekVGT.png In the following HTML snippet: <tr *ngFor ...