What error am I making when attempting to validate an email address with RegExp?

I have been attempting to verify the format of an email address using the script below, but I seem to be making a mistake somewhere. When I try to match the reg_1 pattern with str_1, str_2, str_3, I consistently get a false result. Can anyone help me understand why?

var reg_1 = /^[a-zA-Z][0-9_.][@]{1}[a-zA-Z0-9][.]{1}[a-zA-Z0-9]$/;
var id_1 = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2152544940484d4654515540111261464c40484d0f424e4c">[email protected]</a>";
var id_2 = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5d4f4a4e5b14494f525b53567a485f5e535c5c14595557">[email protected]</a>";
var id_3 = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e390968b828a8fbc8496939782d3d0a38c958acd808c8e">[email protected]</a>";

document.write(reg_1.test(id_1));
document.write("<br / >" + reg_1.test(id_2));
document.write("<br / >" + reg_1.test(id_3));

Answer №1

Your grasp of the character class notation [...] appears to be a bit off. To clarify, [a-zA-Z][0-9_.] signifies "a letter from a to z or from A to Z, followed by a digit from 0 to 9 or underscore _ or dot .".

Based on your intentions, it seems like you're aiming for:

var reg_1 = /^[a-zA-Z0-9_.]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/;

In addition to necessary modifications, I tidied things up a bit: specifically, I replaced [@] with just @ (no need for a character class) and [.] with \. (because you want to match a dot and not any character), and I omitted the {1} since it's implied anyway.

(Keep in mind that this regex isn't a catch-all for validating e-mail addresses. The complexity of e-mail addresses necessitates actually sending an e-mail to confirm its validity!)

Answer №2

One key aspect to note is that you are searching for a sequence that starts with two specific characters and is followed by an @ symbol, yet none of the email addresses you have provided follow this pattern.

Answer №3

Avoid making this mistake. I was just in the middle of drafting a blog post explaining why this method is not effective: How to Properly Validate an Email Address

Simply use a regular expression like the one below for better results:

var emailRegex = /.+@.+\..+/;
console.log(emailRegex.test("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98edebfdead8fde0f9f5e8f4fdb6fbf7f5">[email protected]</a>")); // Output: "true"
console.log(emailRegex.test("www.example.com")); // Output: "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

What could be the reason for the appearance of this error message: 'Illegal arguments: undefined, string'?

Currently, I am in the process of developing a node.js application where I have created a backend API specifically for user registration. However, when testing it using Postman, I encountered an error message stating 'Illegal arguments: undefined, str ...

Need a tool for validating forms?

I am currently facing some confusion with the UI Validation plugin that we are using. Within our application, we employ Spring MVC, Jquery & Bootstrap. As we delve into UI development, we have encountered uncertainty in selecting an appropriate Validation ...

Tips for efficiently deconstructing JSON arrays, objects, and nested arrays

I'm attempting to destructure a JSON file with the following structure: [ { "Bags": [ { "id": 1, "name": "Michael Kors Bag", "price": 235, "imgURL" ...

Retrieving text content from a file using React

I've been experiencing difficulties with my fetch function and its usage. Although I can retrieve data from the data state, it is returning a full string instead of an array that I can map. After spending a few hours tinkering with it, I just can&apos ...

The for...of loop cannot be used with the .for property since it is not iterable. (Is

let arr = [{ category: 'music', views: 20 }, { category: 'abc', views: 32 }, { category: 'bob', views: 20 } ] for (const [key, value] of arr) { console.log(key, value) } console.log(Array ...

Exploring the differences between an XMLHTTP request and a string and establishing a callback mechanism

After being a silent observer for quite some time, I've finally mustered up the courage to make my first post here, so please be kind... My journey with Javascript has just begun, and although I plan on delving into jQuery eventually, for now, I am f ...

Encountered a problem in Node.js when attempting to generate a CSV file using Bot Framework

I am currently working on a chatbot project using the Microsoft Bot Framework with Node Js. My goal is to provide the user with a CSV file upon request. However, I have encountered an issue with the format of the downloaded file 'prova.csv' not ...

What are your thoughts on the practice of utilizing the useState hook within a component to send data to its parent component?

I have been working on developing an Input component that can be dynamically used in any page to store input values. The component also includes an attribute called getValue, which allows the parent component to access the input value. In my App.js file, I ...

What is the best way to accurately establish a new name for the evolving scope

var tags_offset=[]; $scope.getRelations = function(id, ref, subRef=0){ tags_offset[ref+'-'+subRef]=0; $http.get( CONS.appHttp+ '/tags.php?ID='+id +'&ref='+ref +'&contentType='+subRe ...

Error message from sails.js: `req.target` is not defined

Experiencing a problem where req.target sometimes returns undefined, causing issues with other functionalities dependent on req.target. Seeking assistance to resolve this issue. Appreciate any help! ...

Create a feature that allows users to view photos similar to the way it

I want to incorporate a Twitter feed on my website that displays images posted. Instead of having the images redirecting users to Twitter when clicked, I would like them to reveal themselves underneath when a link labeled "View Photo" is clicked, and then ...

Utilizing AJAX to integrate the Google Maps Direction API

Currently, I am developing a small website that utilizes the Google Maps API and AJAX to load directions based on selected locations from a dropdown menu. The database stores latitude and longitude coordinates of various locations, which are retrieved via ...

Modify the hover color of <TextField /> within the createMuiTheme() function

Is there a way to change the borderColor on hover for the outlined <TextField /> Component within the createMuiTheme()? I have managed to do it easily for the underlined <Input /> export default createMuiTheme({ MuiInput: { &apo ...

Using AngularJS to display multiple objects in the same ng-repeat loop

Is it possible to display two objects simultaneously in ng-repeat? <tr data-ng-repeat="target in targets |session in sessions |filter:query | orderBy:orderProp"> ...

Is it possible to assign a different array to a variable in JavaScript?

I'm facing an issue with manipulating arrays in JavaScript within a function. This problem arises from an exercise found in the book Eloquent JavaScript, focusing on two specific functions: reverseArray(): designed to produce a new array that is the ...

JavaScript Language Conversion Templating

I'm currently revamping the frontend for Facebook's internationalization XFBML tag, which has been nonfunctional for a while. I'm almost done with the updates but I have hit a roadblock: swapping out tokenized translations without losing dat ...

Pass the $scope object from a controller to a modal controller

I am facing an issue with transferring the $scope variable from ctrlone to ctrltwo, which is a modal window on my page. When I open the modal in ctrlone, my code looks like this: var modalInstance = $modal.open({ templateUrl: 'Modal.html&ap ...

My ejs page is not showing up because a variable has not been defined

I am facing an issue with an undefined variable causing my EJS page to not display properly when an if statement is included. Removing the if statement allows the page to render, but the presence of the undefined variable and if statement triggers an error ...

Hiding timestamps on an interactive transcript: A step-by-step guide

I am in the process of creating personalized interactive ebooks based on a similar website found here: This website utilizes a VTT file along with an audio file. Although the JavaScript code requires time stamps, I would like to hide them for better read ...

Unwrapping Promises in Angular for Seamless Resolution

I recently started working with Angular and found myself in a large project. I encountered a simplified version of my code below: var beforeClose = function() { var closeDeferred = $q.defer(), a = $q.defer(), b = $q.defer(), c = $q.defer() ...