2

In my HTML form, I would like to use a button for submitting a form instead of input type submit. I have got a javascript code to give an error if the email if empty, also to prevent the form from submitting. However, the code does not seem to work and I get this error: Cannot GET /submit The weird thing is that the code works here in stackoverflow when you run it!

const email = document.getElementById('email');
const form = document.getElementById('form');
const emailMessage = document.getElementById('email-message');

form.addEventListener('submit', e => {
  if (email.value === '' || email.value === null) {
    emailMessage.innerHTML = 'where is the email';
    e.preventDefault();
  } else {
    return true;
  }
});
  <form id="form" action="submit">
            <input id="email" type="email" />
            <button type="submit">Go</button>
            <p id="email-message"></p>
          </form>
Hesam Alavi
  • 149
  • 3
  • 12

2 Answers2

8

Why not just use the required attribute? No JS necessary

<input id="email" type="email" required>

This will check if the email field is not empty and additionally entered string is a valid email format.

Note that HTML "required" does not work in safari browser whose version less than Safari 10.1 (May 2017)

Edit: To display a custom message, subscribe to the invalid event

const email = document.getElementById('email');
email.addEventListener('invalid', function(e){
   if (email.value == '')
     email.setCustomValidity('Where is the email?'); 
   else if (email.validity.typeMismatch)
     email.setCustomValidity('Email address be invalid!'); 
});

You can learn more about Form Validation at Mozilla

Whip
  • 1,891
  • 22
  • 43
0

Your code works fine. try this

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<form id="form" action="submit">
    <input id="email" type="email"/>
    <button type="submit">Go</button>
    <p id="email-message"></p>
</form>

<script>
    const email        = document.getElementById('email');
    const form         = document.getElementById('form');
    const emailMessage = document.getElementById('email-message');

    form.addEventListener('submit', e => {
        if (email.value === '' || email.value === null) {
            emailMessage.innerHTML = 'where is the email';
            e.preventDefault();
        } else {
            return true;
        }
    });
</script>
</body>
</html>
  • The code works when I run it in stackoverflow, but on my locally, when I click the Go button, it goes to a page with this message: Cannot GET /submit – Hesam Alavi Feb 17 '20 at 08:43