Home > front end >  How to check email input from HTML button in Javascript
How to check email input from HTML button in Javascript

Time:02-14

The outcome I want:

  1. Click the button (div class button)
  2. Check what is inputted (div class email)
  3. If it isn't an email, return an error that it isn't an email.
<div >
<input type="text" name=""  placeholder="Email Address">
</div>
<div  > <h2 > Request Access </h2> </div>
</div> 

I don't know where to start from JavaScript code. Any tips will help.

CodePudding user response:

Use regex to validate things like emails, passwords, usernames, etc. It's really powerful and can do a ton.

Solution:

<form >
    <input type="email"  placeholder="Email Address" />
    <button type="submit">Request Access</button>
    <p id="error" style="color: red; display: none">Please enter a valid email</p>
</form>

<script>
    const email = document.querySelector('.emailInput');
    const submit = document.querySelector('button');
    const error = document.querySelector('#error');

    const showError = () => {
        error.style.display = 'block';
    };

    submit.addEventListener('click', (e) => {
        e.preventDefault();
        if (!email.value.match(/[^@ \t\r\n] @[^@ \t\r\n] \.[^@ \t\r\n] /)) {
            return showError();
        }

        console.log('success');
    });
</script>

  • Related