Ensuring email address validity within Angular 2.3.1

I'm working on implementing email validation in an Angular 2 form, but I'm facing some challenges making it function properly.

Below is the code snippet from my register.html form:

<div class="row">
<div class="col-lg-10 col-offset-2">
<div class="well bs-component">
  <form name="registerForm" class="form-horizontal" (ngSubmit)="onSubmit(email, password, name, surname, username, homephonenumber, mobilenumber)" >
    <fieldset>
      <legend>Register</legend>
      <div class="form-group">
        <label for="username" class="col-lg-2 control-label">UserName</label>
        <div class="col-lg-10">
          <input type="text" class="form-control" name="username" [(ngModel)]="username" placeholder="Username"  required minlength="4" maxlength="20">
        </div>
      </div>
      <div class="form-group">
        <label for="email" class="col-lg-2 control-label">Email</label>
        <div class="col-lg-10">
          <input type="text" class="form-control" name="email" [(ngModel)]="email" placeholder="Email"  required minlength="4" >
          <div *ngIf="email.dirty && !email.valid" class="alert alert-danger">
                        <p *ngIf="email.errors.required">Email address is required.</p>
                        <p *ngIf="email.errors.incorrectMailFormat">Email format is invalid.</p>
          </div>
        </div>
      </div>
      <div class="form-group">
        <label for="password" class="col-lg-2 control-label">Password</label>
        <div class="col-lg-10">
          <input type="password" class="form-control" name="password" [(ngModel)]="password" placeholder="Password"  required minlength="4">
        </div>
      </div>
      <div class="form-group">
        <div class="col-lg-10 col-lg-offset-2">
          <button type="reset" class="btn btn-default">Cancel</button>
          <button type="submit" class="btn btn-primary">Register</button>
        </div>
      </div>
    </fieldset>
  </form>
</div>

In my register.component.ts file, the following code is implemented:-

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {UserService} from 'app/services/user.service';
import {FormGroup, FormControl, Validators} from "@angular/forms";

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  registerForm: FormGroup;

  constructor(private _userService:UserService, private _router:Router) { }

  ngOnInit() {
    this.registerForm = new FormGroup({
      email: new FormControl('', this.validateEmail)
    });
  }

    onSubmit(email, password, name, surname, username, homephonenumber, mobilenumber){
    this._userService.register(email, password, name, surname, username, homephonenumber, mobilenumber)
      .subscribe((result) => {
      // if(result.access_token != null) {
      //   this._router.navigate(['']);
      // }
    });
  }

  validateEmail(c: FormControl) {
    let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    return EMAIL_REGEXP.test(c.value) ? null : {
      validateEmail: {
        valid: false
      }
    };
}

Do I need to add any additional configurations to ensure the validation functions correctly?

Thank you for your assistance and time.

Answer №1

HTML5 now includes an email type that automatically validates.

<input type="email" class="form-control" name="email" [(ngModel)]="email" placeholder="Email"  required minlength="4">

Alternatively, you can use ng-pattern to specify a custom validation pattern.

<input ng-pattern='/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<<>()[\]\.,;:\s@\"]{2,})$/i' type="email" name="email" class="form-control" ng-model="email" required="" />
          <p class="help-block error-block">Enter a valid email address.</p>

Answer №2

Here is a different approach to solve the issue:

 HTML:

     <form id="frmForgetPwd" name="frmForgetPwd" #frm="ngForm">
                            <div class="form-group">
                                <label>Enter Your Email Address</label>
                                <input type="email" class="form-control" focus
                                       id="emailID" name="emailID" autofocus
                                       #email="ngModel"
                                       ngModel
                                       required>
                            </div>
                            <button type="submit (click)="forgotPassword(email.value)">
                                Verify Email
                            </button>
                        </form>

    component:

            forgotPassword(emailid: string) {
                this.emailErrors = [];
                if (emailid == "") {
                    this.emailErrors.push(new error("invalidemail",Messages.EMAIL_IN_VALID));
                    return false;
                }
                let EMAIL_PATTERN = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                if (!EMAIL_PATTERN.test(emailid)) {
                    this.emailErrors.push(new error("invalidemail",Messages.EMAIL_IN_VALID));
                    return 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

Having trouble retrieving information from ajax to php

I'm struggling to understand why this code is not functioning as expected: idcurso= res[0]; idusuario= res[1]; semana= res[2]; fecha=res[3]; asistencia= true; $.ajax({ type: "POST", url: '/test/7/tomarasistencia.php', data: { ...

What is the reason for this MongoDB document consistently having the identical nanoid?

Although I've managed to find a solution, my main concern is understanding the root cause of the bug. In the scenarios below, MongoDB documents are being created with identical id and date values respectively. id: { type: String, required: tru ...

Trigger a function upon clicking a DOM element in Vue.js

My goal is to trigger a function whenever I click on elements in the DOM that have a specific class. Despite my efforts, the functionality doesn't seem to work, and no errors are being reported. Here's the relevant code: methods: { ...

Issues with the Aurelia TypeScript Skeleton

Downloaded the aurelia skeleton and everything works fine when using gulp watch. However, running it from Visual Studio results in several errors: Severe Code Description Project File Line Suppression State Error TS6059 The file 'C:/ ...

Is it possible to have a single listener for all events within the jQuery event namespace?

Is it possible to create a handler that can listen to ALL events within a specific namespace in jQuery using $.fn.on, off, and trigger functions? For example: $(window).on(".event_namespace", function(e){ //handler }); $(window).trigger("testEvent.e ...

What is the method to show text exclusively upon hovering the mouse?

Here is a sample that I'm working with: link HTML CODE: SED PERSPICIATIS Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore ...

What is the process for adding a custom header when making an ajax call in a datatable?

Currently, I am utilizing datatables and need to include a custom header for specific server-side requirements. Can anyone provide guidance on how to send a custom header when navigating to the next or previous pages using jQuery datatables? Additional ...

"Utilize Ionic to subscribe the back button and close an internal div with ease

I have a div called "Search Filters" that appears when the condition this.show_filters == true is met. I am now attempting to use the Android back button to change this variable to false. async toggleFiltersWindow(){ console.log('#1 toggleFilters( ...

SVG polyline animation that persists seamlessly

In my TypeScript code, I have implemented a function that creates a polyline based on 4 different points (x1y1, xCy1, xCy1, x2y2), where Xc represents the half distance between x1 and x2 on a plane. This polyline does not form a circular shape. private cre ...

When the cursor hovers, a drop-down menu appears simultaneously

Currently utilizing the Bigcommerce stencil theme, I have encountered an issue where both dropdown menus appear when I hover over a link. My goal is to have only one dropdown menu pop up when hovering over a specific link. https://i.sstatic.net/paVoY.png ...

Execution of Javascript code does not provide the expected output when run via VS Code

I've attempted numerous times, but the desired output doesn't appear when I run it through VS Code. However, this code runs smoothly and produces the desired output when executed in Replit's online code editor. Can anyone offer assistance? l ...

Error encountered when trying to populate the second dropdown in the change event

Having some difficulty with populating a second dropdown from a mysql result. The code seems fine, but there must be something off. The value being passed correctly to $rtvcompany = $_GET['rtvcompany']; from loadboxRtvaddr.php?rtvcompany= in PHP ...

Can you help me streamline the code for the Sign Up Form app using React and jQuery?

Hi everyone, this marks my debut post on StackOverflow as I embark on the journey to become a full stack developer. To enhance my skills, I've been using FrontEnd Mentor for practice and managed to solve a challenge with the code provided below. Any s ...

Choosing a request date that falls within a specified range of dates in PHP Laravel

In my database, I currently store two dates: depart_date and return_date. When a user is filling out a form on the view blade, they need to select an accident_date that falls between depart_date and return_date. Therefore, before submitting the form, it ne ...

Verify the duration of the video upon uploading - Angular

I am having trouble checking if the video I uploaded is longer than 30 seconds, and I am struggling to find a suitable example. Below is the code snippet that includes size checking among other things: readVideoUrl(event: any) { this.videoFile = []; ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

Disappear and reappear: the magic of text on page reload with javascript onclick event

I have a JavaScript function that displays text when a button is clicked. The issue I am facing is that the text appears momentarily and then disappears after the page is reloaded. Below is the paragraph that shows the text once the button is clicked: &l ...

What is the issue with assigning type {intrinsicattributes & true} or type {intrinsicattributes & false} in a React and TypeScript environment?

I am facing an issue with the following code snippet: function Parent() { const count1 = 2; const count2 = 4; const isCount = count1 < 0 || count2 < 0; //setting isCount here return show ? ( <Dialog> ...

How can I retrieve the Azure subscription IDs of the currently logged in user using @azure/msal-angular?

I successfully authenticated a user using @azure/msal-angular and received the id_Token, access_Token and tenant Id. Now I am looking to retrieve the logged in user's azure subscriptions. Is there a way to achieve this through msal or are there any Ja ...

D3.js: Exploring the beauty of layered legends

I have a question regarding creating legends with triangle shapes. Specifically, I am trying to create two triangles representing "Yes" and "No". However, when I run the code below, the triangles end up overlapping each other. In an attempt to separate t ...