Tips for utilizing Regular Expressions to validate emails in Typescript

I need help validating email and date fields from an Excel file using a TypeScript Angular app.

Despite trying to use regular expressions for validation, the result always shows false for a correct email address.

If anyone can assist me in properly validating emails and dates, it would be greatly appreciated.

Below is the code snippet that I have implemented:

Component:

import {  Component } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import {UploadService} from '../services//upload.service';


import { FileUploader ,FileItem,ParsedResponseHeaders,FileLikeObject} from 'ng2-file-upload';

import { SpotCheck } from '../models/SpotCheckFields';  

@Component ({  
    selector: 'my-app',  
    templateUrl:'./excelUpload.html',
    providers:[UploadService]
})  

export class ExcelUploadComponent  { 

    public SpotChecklist: SpotCheck[];
    public project_master:any[];

    uploader:FileUploader;

    constructor(private uploadservice: UploadService ){
        this.SpotChecklist=[];
        this.project_master=[];
    }
    ngOnInit(): void {
        this.uploader = new FileUploader({
            url: 'http://localhost:5000/upload'
            // headers: [{name:'Accept', value:'application/json'}],
            // autoUpload: true,
        });
        this.uploader.onErrorItem = (item, response, status, headers) => this.onErrorItem(item, response, status, headers);
        this.uploader.onSuccessItem = (item, response, status, headers) => this.onSuccessItem(item, response, status, headers);

        // retrieve projectmaster details
        this.getProjectMaster("","SELECT PROJECT MASTER");
    }

    onSuccessItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
        //console.log("onSuccessItem " + status, response, item);  
        this.SpotChecklist = JSON.parse(response); //success server response

        var data = this.validateRow(this.SpotChecklist);

        console.log(data);  
    }

    onErrorItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
        let error = JSON.parse(response); //error server response
    }

    validateRow(lst:any[]) : SpotCheck[]
    {
        var i:number;
        for(i=0;i<lst.length ;i++)
        {
            var validation_message:string="";
            var blnErrOccured:boolean=false;

            if(!this.isEmail(lst[i].RESPONSIBLE_PERSON_EMAIL_ID))
            {
                validation_message=validation_message+ "," +"RESPONSIBLE_PERSON_EMAIL_ID is invalid"
                blnErrOccured=true;
            }

            lst[i].VALIDATION_RESULT=validation_message;
        }
        return lst;
    }

    isDate(date:string) {
        // return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
    }

    isEmail(search:string):boolean
    {
        var serchfind:boolean;

        regexp = new RegExp('/^(([^<>()\[\]\\.,;:\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,}))$/');

        serchfind = regexp.test(search);

        console.log(serchfind)
        return serchfind
    }

    getProjectMaster(project_code:string,Flag:string):any
    {  
        this.uploadservice.getProjectMaster(project_code,Flag).subscribe(
            response=> {
                this.project_master= response[0];
                return response;
            },
            error=> {
                console.log("ERROR: ",error);
                console.log(error.json()); //gives the object object
            },
            () => {
                console.log("Completed");
            }
        );
    }
}

Answer №1

The issue lies in the provided regex format. Please remove the single quotes (') and use it in this way

regexp = new RegExp(/^(([^<>()\[\]\\.,;:\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,}))$/);

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

Issues with displaying all series values on hover in Highcharts tooltips are being experienced

https://i.sstatic.net/7NVBM.gif The desired outcome is for the tooltip to show all 7 bar values for a specific yAxis entry. However, it currently only displays the values dynamically for 3 to 7 of the bar values based on the cursor position in the yAxis ...

Managing dynamic text within a label using Playwright

In my Playwright Typescript test, I have the following code snippet: await page.goto('https://demoqa.com/'); await page.getByLabel('Optionen verwalten', { exact: true }).click(); await page.locator('label').filter({ hasText: & ...

Utilizing jQuery to apply multiple classes simultaneously?

What is the purpose of allowing multiple classes to be added? Is there any real benefit to this feature or is it just unnecessary complexity? I attempted to utilize it, but found that it serves no practical function. ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

Guidelines for toggling text visibility based on a randomly generated number with if statements in vanilla JavaScript

I am currently attempting to showcase some intricate text alongside an image once a button is clicked. At the moment, I have successfully implemented the functionality to display a random image when the button is clicked. However, I am encountering diffic ...

Is it possible to constantly retrieve data at one-second intervals in NextJS using getServerSideProps?

Is there a way to continuously fetch API data in NextJS using SSR (getServerSideProps) every second? This would involve the client making a request to the server every one second to receive the most up-to-date API data. Any suggestions? export const getS ...

What is the best way to include 'px' within a calc function?

Here's my current situation: style={{ width: 'calc(100% - 300px)' }} I'm aiming for something like this: let myWidth: number = 300; style={{ width: 'calc(100% - {myWidth})' }} The example above doesn't work as expect ...

Utilizing Discord.js to Transfer Users Between Voice Channels

Does anyone know the most updated method for creating a discord js bot that can move users to different voice channels? I've been encountering errors with the solutions I found online. Currently, I'm manually setting it to a specific channel for ...

What is the best way to eliminate duplicate values from an Array in ReactJS?

Hi there, I'm new to JavaScript and React. I need some help with a project I found on the React blog. I want to try solving it in my own way. This is the content of todoList.js: const todoList = [ {category: 'Sporting Goods', price: &a ...

Leverage JavaScript to display images based on the class of the element

I am looking to display specific logos based on a user's search for a product within a certain category. Initially, the logo image element is hidden (display none) and will be assigned a class corresponding to the category ID. The category ID will det ...

Simplifying class selection in event delegation with jQuery by using serial numbers

Creating a web quiz involves dynamically generating each question and option element based on an array. Here is the script I am using: function displayQuestions(){ for(let i = 0; i < QuesPartA.length; i++){ $(".questionBox").append ...

Converting a JSON array into a singular object using Node.js

I am struggling to convert a JSON array into a single object. Here are the details: Array: [{ "item-A": "value-1" }, { "item-B": "value-2" }] Expected Result: { "item-A": "value-1", "item-B": "value-2" } I have attempted various methods but none have yi ...

The element is implicitly assigned an 'any' type as the expression of type 'string' is unable to be used as an index within the type '{...}'

Trying to improve my react app with TypeScript, but encountering issues when typing certain variables. Here's the error message I'm facing: TypeScript error in /Users/SignUpFields.tsx(66,9): Element implicitly has an 'any' type becaus ...

Switching out one block of HTML with another in JavaScript is a powerful way to dynamically update

I am working on creating a feature on a webpage where clicking a button will change the HTML code inside a specific div. Essentially, I want to be able to update the content of a div by simply clicking a link. Here are two different sets of HTML code: Co ...

Executing Multiple Writes in Firestore Using Batch Operations

I have a situation where I need to update multiple references to different documents in my database within a single batch.commit operation so that I can monitor the count. To achieve this, I am using increment to update the field values. While this appro ...

In relation to the portability of node.js and npm libraries

Is it possible to execute Javascript code written using node.js and libraries installed via npm (such as xlsx-populate) on a different computer without those dependencies installed? Thank you ...

Modify color - Angular Pipe

I needed to make 2 transformations on my Angular template. The first transformation involved changing the direction of the arrow depending on whether the number was negative or positive. I achieved this using a custom Pipe. The second transformation was t ...

Cypress: harnessing the power of regular expressions within jQuery selectors for the ":contains()" method

Trying to use Cypress along with a regular expression to target an element that includes specific text. The following get() function successfully works: cy.get('[data-cy=tile]').contains(new RegExp(myVar)) However, the following command does no ...

Angular 2 eliminates the need for nesting subscriptions

Is there a way to streamline nested subscriptions like the code snippet below? I want to extract values from the subscription for better organization, but using a global variable won't work because the subscription hasn't received the value yet. ...

Storing user data on the client side of a website is most effectively accomplished by

I am looking to incorporate the following features: I would like to personalize the user experience by greeting them with their login name on the webpage (e.g. 'Hello, Fred!'). I also want to display or hide certain content based on the user&apo ...