What is the best way to ensure email address validation is done perfectly every time?

Can someone assist me with validating email addresses correctly? I am able to handle empty fields, but now I need a way to identify and display an error message for invalid email addresses. How can I modify my validation process to check for improper email formats?

This:

if (x == "what goes here?")
   {
    document.getElementById("demo").innerHTML = "Please enter a proper email address";
    document.getElementById("demo").style.display = "block";
    return false;
  }

The placeholder "what goes here?" needs to be replaced with the correct value.

Without further ado, here is the code snippet for the website:

<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css2?family=PT+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
<style>
body {
  font-family: 'PT Sans', sans-serif;
}
p#demo {
  padding: 5px;
  background: rgba(255,0,0,0.2);
  border: red solid 1px;
  color: red;
  display: none;
  max-width: 140px;
  text-align: left;
  font-size: 12px;
  margin-left: 2px;
  font-family: 'PT Sans', sans-serif;
}
input[type="submit"] {
  background-color: red;
  border: none;
  font-family: 'PT Sans', sans-serif;
  font-size: 15px;
  font-weight: 700;
  text-transform: uppercase;
}
input[type="email"] {
  padding: 4px;
  }
input[type="email"]:focus {
  outline: none;
}
</style>
<script>
function validateForm() {
  var x = document.forms["myForm"]["EMAIL"].value;
  if (x == "") {
    document.getElementById("demo").innerHTML = "Email address is required.";
    document.getElementById("demo").style.display = "block";
    return false;
  }
   if (x == "what goes here?")
   {
    document.getElementById("demo").innerHTML = "Please enter a proper email address";
    document.getElementById("demo").style.display = "block";
    return false;
  }
}
</script>
</head>
<body>

<form name="myForm" action="https://gmail.us19.list-manage.com/subscribe/post?u=f206f10b38a504434c650c6bf&amp;id=5ce815006b" onsubmit="return validateForm()" method="post" >
  <p id="demo"></p>
  <input type="email" name="EMAIL">
  <input type="submit" value="Sign up!">
  
</form>

</body>
</html>

Answer №1

Recently, I was working on a form that required email address validation. To achieve this, I implemented a Regular Expression:

^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\]?)$

You can use the above expression as follows:

function validateEmail() {
  document.getElementById("demo").innerHTML = "Please enter a valid email address";
  document.getElementById("demo").style.display = "block";
}
<form action="">
  <input type="email" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0- 9\-]+\.)+))([a-zA-Z]{2,}|[0-9]{1,})(\]?)$" placeholder="Email Address" oninvalid="validateEmail()" />
  <div id="demo"></div>
  <input type="submit" />
</form>

If you wish to disable the default HTML5 validation bubble, you can add the following JavaScript code (Please note: This will impact the entire form):

document.addEventListener('invalid', (function(){
    return function(e) {
      //prevent the browser from showing default error bubble / hint
      e.preventDefault();
      // optionally fire off some custom validation handler
      // myValidation();
    };
})(), true);

This approach will retain your customized validation while disabling the default behavior. I hope this solution proves beneficial for you!

EDIT: While I recognize that using regular expressions (RegEx) may not be ideal in all situations, I have found this particular one to be reliable across various forms.

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

Use jQuery to compare the input values whenever they are modified

I am trying to synchronize the input values of two inputs as they are typed in. The code I have seems to work sometimes, but not consistently. Here is the code snippet: $('#google-querynav').keypress(function() { var text = $(this).val(); ...

Why is it possible for the EXPRESS+EJS template to access CONFIG without explicitly passing it when rendering?

Currently exploring my knowledge of node.js alongside express and the ejs template. As I delved into some code, I stumbled upon the fact that they were able to invoke config in the template without explicitly passing it as a variable during rendering. You ...

Use ajax to load a webpage into a specific div, then reload the same div after submitting

I have a webpage that includes hyperlinks and a content area with an id of "contentarea" where the results from these hyperlinks are displayed. When a user clicks on the "Search" link, the page search.jsp loads, which contains a submit button and a form ...

Height of the liquid division

I'm encountering an issue with my CSS layout. I have a container containing two columns, each styled with the following CSS: #project-desc{ float: left; width: 500px; } #project-images{ float: right; width: 300px; } I've use ...

Material UI categorizing iPads with a width of 768px and a height of 1024px as belonging to the small

I am facing a challenge with the layout of my app on different screen sizes. To address this issue, I am utilizing Material UI's breakpoints to control the layout based on the screen size. According to the documentation, screens categorized as small ...

AngularJS - $scope.$destroy does not eliminate listeners

I am currently exploring how to develop my own "one-time binding" functionality for AngularJS version 1.2 and earlier. I came across this response which explains the process of creating a custom bindOnce directive. Upon using the provided directive: a ...

Tips for overlaying text onto a MaterialUI icon

https://i.stack.imgur.com/cFr5Y.pngI am currently working on a project that requires me to overlay a number on top of an icon. Specifically, I am utilizing the MaterialUI ModeComment icon and attempting to display text over it. Despite trying the following ...

What could be causing my scrollable div to not function properly within a Bootstrap modal?

I am facing a frustrating issue. I have a simple DIV element that I want to make scrollable, containing a table inside it. The process should be straightforward as I have a separate .html file with the code that functions correctly. Here is an excerpt of ...

I am having trouble with an undefined variable in my expressjs server.js file. How can I properly reference

When setting up ExpressJS, I have a file named server.js where the following code is executed: import { call_method } from '../hereIam.mjs'; const process_db = async () => { console.log(this); // undefined call_method(this); }; console. ...

Why Isn't the Element Replicating?

I've been working on a simple comment script that allows users to input their name and message, click submit, and have their comment displayed on the page like YouTube. My plan was to use a prebuilt HTML div and clone it for each new comment, adjustin ...

Optimal method for linking NodeJS and Angular in a seamless integration

I am currently working on developing a web application that integrates a Node server as the backend and Angular for the front end. At the moment, my application consists of two JavaScript files: server.js and controller.js. Below is the code snippet for ea ...

Error: Unable to access the 'nom_gr' property of null - encountered in Chrome

<ion-col col-9 class="sildes"> <ion-slides slidesPerView="{{nbPerPage}}" spaceBetween="5"> <ion-slide *ngFor="let slide of lesClassrooms; let i = index" (click)="saveCurrentSlide(i)"> ...

Searching for a specific row of data by ID in a massive CSV file using Node.js

Can someone recommend an npm package that is ideal for iterating over a csv file, locating a specific value, and updating/appending to that particular row? I don't have any code to display at the moment as I'm in the process of testing different ...

Struggling with a dynamic HTML table using Mustache and Icanhazjs technologies

I am encountering an issue while attempting to construct a dynamic table using Icanhazjs (Mustache). The table data is consistently rendered outside the table tag, resulting in my data not being displayed within the table itself. To observe the output, pl ...

Does Vue.js interfere with classList.remove functionality?

When working with Vue.js, I encountered an issue where elements would briefly flash curly braces to the user before being hidden. To combat this problem, I implemented the following solution: HTML: <div class="main hide-me" id="my-vue-element"> ...

Mastering HTML Tag Styling within Visual Studio

I'm looking for assistance on how to automatically format HTML tags using the Ctrl + K, Ctrl + D shortcut. For example: <label id="myLabelId">Hello</label> should be reformatted to: <label id="myLabelId"> Hello </label> ...

Developing a robust system for managing classnames

I have a question regarding the article I found on Quora about Facebook's CSS class names structure. They mentioned that both Facebook and Google use a build system to convert developer-friendly class names into shorter ones to save bandwidth and crea ...

There was an unexpected error: Unable to access the 'icon' property of null

Whenever I try to edit a tab using the form, an issue arises. If I open the dialog box by clicking the edit icon and then hit save without altering the icon field, I receive an error message stating Uncaught TypeError: Cannot read property 'icon' ...

Creating a loop with resolves to navigate through states in AngularJS with ui-router requires the use of a closure

Within our AngularJS app, I am dynamically creating states using ui-router. Consider an array of states like the following: const dynamicStates = [ {name: 'alpha', template: '123'}, {name: 'bravo', template: '23 ...

Which specific html container or element can be found on the mymsn pages?

When accessing mymsn, users have the ability to personalize the content and layout of their webpage. I am curious about what type of container is being utilized for this customization - does it involve an html element, or perhaps javascript, or something e ...