40

I have an requirement to validate email and date fields from an Excel file using typescript Angular app.

And I am trying to validate using regular expression but the result returns always false for a correct email address.

Can anyone help me to validate the email and dates?

Below is the code I have written

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");
            }
        );
    }
}
4
  • Actually I have copy the code from the above link it self. Commented Sep 22, 2017 at 18:11
  • what's the output of your code. does it validate incorrectly? or not validating at all? any errors in console? Commented Sep 22, 2017 at 18:13
  • no error!!! it just returns false for correct email address also Commented Sep 22, 2017 at 18:15
  • It's not realistic to use a regex. Use the built-in parsers for URL and Date, passing in the values and see what happens (Nodejs and the browsers get regular updates for these things, so why duplicate concerns generally?). In the case of URLs simply add a protocol before. see stackoverflow.com/a/57966778/965666 This has been asked so many times.
    – jimmont
    Commented Sep 17, 2019 at 23:40

1 Answer 1

45

Problem is with the regex format given. Give it without quotes (') like this

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,}))$/);
4
  • Yeah.. working... thank you Commented Sep 22, 2017 at 18:25
  • Might not work for something other than english. Will post what I use. Commented Oct 5, 2017 at 20:47
  • this example returned true. che@ghehxhe Commented Jan 21, 2019 at 21:46
  • 1
    @AbdullahNurum actually this is true, as like localhost is a valid domain. Commented Jan 7, 2020 at 9:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.