How can I perform email validation using Angular 6?

I am working on an Angular6 form that includes a field for email input.

Currently, the email field has proper validation which displays an error message when an invalid email is entered. However, even if the error message is shown, the form is still saved when the "Save" button is clicked. How can I display the error message without saving the user upon clicking?

An important requirement is that the "Save" button should not be disabled.

Below is the code from user.component.html:

<form method="post" enctype="multipart/form-data>
  <mat-form-field>
   <input matInput placeholder="Enter your Username" [(ngModel)]="userObj.userName" name="username" required>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Enter your email" [formControl]="email" [(ngModel)]="userObj.emailid" name="emailid" required>
    <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
  </mat-form-field>                   
</form>

<button mat-raised-button color="primary" (click)="saveNewUserDetails()">Save User</button>

And here is the code from user.component.ts:

import {FormControl, Validators} from '@angular/forms';
email = new FormControl('', [Validators.required, Validators.email]);

getErrorMessage() {
  return this.email.hasError('required') ? 'You must enter a value' :
    this.email.hasError('email') ? 'Not a valid email' : '';
}

saveNewUserDetails(){
  if(this.userObj.userName.trim() != ''){
    const formData = new FormData();
      formData.append('username',this.userObj.userName);
      formData.append('emailid',this.userObj.emailid);
      this.userService.saveNewUserDetails(formData).subscribe(
       (data) => {
         console.log("user is saved successfully");
       }           
     )
   }
  }       

Answer №1

When working with the saveNewUserDetails() function, make sure to include the following:

saveNewUserDetails() {
    if (this.email.invalid) {
      // Do Not proceed with submission
    } else {
      // Proceed with submission
    }
}

Alternatively,

Consider adding [disabled]="email.invalid" to your button for better user experience:

<button 
  mat-raised-button 
  [disabled]="email.invalid" 
  color="primary" 
  (click)="saveNewUserDetails()">
  Save User
</button>

Answer №2

If you prefer not to deactivate the Save button, yet still wish to prevent saving, it's important to inject that information into your save function. If your objective is simply to render the button non-functional, you can achieve this in the template as shown below:

<button mat-raised-button color="primary" (click)="email.valid && saveNewUserDetails()">Save User</button>

However, if you also want to display a notification, handle it in the function (pass the email.valid parameter):

<button mat-raised-button color="primary" (click)="saveNewUserDetails(email.valid)">Save User</button>

saveNewUserDetails(emailValid: boolean) {
  if (!emailValid) {
    // Display a notification or execute alternative actions
    return;
  } 
  // Proceed with your logic when everything is valid.
}

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

Oops! There seems to be an issue with locating a differ that supports the object '[object Object]' of type 'object', like an Array

I'm currently encountering an error that reads: (ERROR Error: NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the key ...

Creating a consolidated System.config mapping for @angular modules using a single .js file

Currently in the process of developing an Angular 2 application, with the specific requirement to consolidate all resulting Javascript files into a single .js file called output.js. Now, the challenge is to incorporate map configuration within System.conf ...

customize your selections in p-multiselect with dynamic choices primeng angular 2

I am currently working on implementing the Primeng datatable. I have put together an array containing headers, fields, and options called headersList. Here is how it looks: { header: "Time", field: "time", options: "timeOptions" }, { header: ...

Can you tell me which version of Angular is the most reliable and stable?

I am currently running version 9.0.7 of Angular. Could someone recommend a stable version of Angular to use? ...

After upgrading to Angular 15, the Router getCurrentNavigation function consistently returns null

Since upgrading to angular 15, I've encountered a problem where the this.router.getCurrentNavigation() method is returning null when trying to access a state property passed to the router. This state property was initially set using router.navigate in ...

a guide to caching a TypeScript computed property

I have implemented a TypeScript getter memoization approach using a decorator and the memoizee package from npm. Here's how it looks: import { memoize } from '@app/decorators/memoize' export class MyComponent { @memoize() private stat ...

The functionality to close a Mat dialog is not functioning properly on Angular 11 with Material 11

I am trying to close the dialog by calling the close function of MatDialogRef instance, but unfortunately it is not working as expected. Within my ShareModule, there are components like HeaderCompose and LoginComponent. The HeaderComponent utilizes the Lo ...

Maintaining search filters across pages in Angular 2 using URL parameters

I am attempting to store certain filters in the URL for my application, so that they can be reapplied when the page is reloaded. I am encountering challenges with Dates (using moment), nullable properties, and special characters (/). When I pass values to ...

Error: Unable to access _rawValidators property of null object

I'm currently facing an issue with formgroup and formcontrol in Angular. When I run ng serve, it's showing an error in the console. Does anyone have a solution for this? TypeError: Cannot read properties of null (reading '_rawValidators&a ...

Angular - Collaborative HTML format function

In my project, I have a function that sets the CSS class of an element dynamically. This function is used in different components where dynamic CSS needs to be applied. However, every time I make a change to the function, I have to update it in each compo ...

`What exactly do auth.guard.ts and the AuthenticationService do in Angular 8?`

import { Injectable } from '@angular/core'; import { AuthenticationService } from './_services'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable({ providedIn: & ...

Discover the best way to cycle through bootsrap modal dialogs using angular

Within my component.ts file, there exists an array: dummyData = ['1', '2', '3']; The objective is to iterate through this array and generate 3 modals displaying values 1, 2, and 3 respectively. Here's a snippet of the ...

How to Retrieve ViewChild Element from within Input Component in Angular 2

Currently, I am utilizing ViewChild to target a specific HTML element within an Angular 2 component. My goal is to access this element from an Input field, but I am struggling with the correct syntax to correctly target the element in question. Below is th ...

Showing Information without NgFor Directives

I have successfully displayed data without using a ngFor loop. However, it is currently showing all the quote information from multiple customers. The CSS is arranged in such a way that the discount div is positioned next to the customerinfo div. Below is ...

Using an array to enforce form validation rules in Angular, including prohibited form values

I am currently developing a basic Angular form with specific validation requirements: The input must not be left empty The input cannot match any of the values stored in the array forbiddenValues. While I understand how to implement the required validat ...

Angular web application can retrieve JSON data from a web API controller, allowing for

I'm currently utilizing ASP.NET Core on the backend and Angular on the frontend. My API delivers data in JSON format from the backend. I've set up a service to fetch the API data, but it's returning 'undefined' at the moment. emp ...

Encountered an error while setting up Angular 2 Server with Express: ERR

My website was built with Angular2 on the frontend and Node/Express on the backend. The frontend runs on port 4200 (run npm build to start it) while the backend runs on port 4201 (npm start). I have a user login management view that works perfectly on loc ...

Ensuring Commitments in the ForEach Cycle (Typescript 2)

Having trouble with promise chains after uploading images to the server in Angular 2 and Typescript. Let's come up with some pseudo-code: uploadImages(images):Promise<any> { return new Promise((resolve, reject) => { for (let imag ...

Tips for updating ion-select option to correspond with the object by utilizing the object's identifier as the value

In my code, I have a select element that looks like this. <ion-select formControlName="location" (click)="clearSectionAndTask()"> <ion-select-option *ngFor="let location of locations" value="{{location.locationId}}"> ...

TypeScript Interfaces: A Guide to Defining and

In my angular2 application, I have created interfaces for various components. One of these interfaces is specifically for products that are fetched from a remote API. Here is the interface: export interface Product { id: number; name: string; } ...