Home > database >  how can i validate a gmail or yahoo email Address using java script and html
how can i validate a gmail or yahoo email Address using java script and html

Time:04-06

how can I check if an email Address contain gmail or yahoo Address? i dont need to find if its a real and active one, just to see if the input value recognized thats its gmail or yahoo. i wrote this code, but its blocking any value on the input and return alert:

const singupVlidation = ()=>{
    let email = document.forms['customerinfo']['email'].value;
    let gmail = '@gmail.';
    let yahoo = '@yahoo.';
    if(email.indexOf(gmail) == -1 || email.indexOf(yahoo) == -1 ){
        alert('invalid Email address, please correct')
        return false;
    }
    else if(true){
        window.location.href="singin.html";
        return true;
    } 
}

heres the html:

<form action="/singup" name="customerinfo" method="post" onsubmit="return singupVlidation()">
            <input  type="email" name="email" placeholder="Email">
            <br>
            <input type="submit" value="NEXT" >
        </form>

if i change the code to look only for "@" then its working, what should i change?

CodePudding user response:

The logic of your if is incorrect. You're using || which means OR while you should be using && which means AND.

This is because what you want to do, translated in english is: If the email doesn't contain @gmail AND the email doesn't contain @yahoo , then give error.

So change your code to

if(email.indexOf(gmail) == -1 && email.indexOf(yahoo) == -1 ){

Furthermore, how you search for @gmail. is not a good method, as you might encounter fake domains like @gmail.myfakedomain.com and you're not considering .ymail.com You could probably be more precise by using a full list of valid domains, e.g. from here and then match the domain exactly instead of doing a string search with indexOf.

e.g.

const singupVlidation = ()=>{
    // Define list of valid domains as an array
    let domain_list = ['gmail.com', 'googlemail.co.uk', 'ymail.com', 'yahoo.com', 'yahoo.it', '......etc'];
    let email = document.forms['customerinfo']['email'].value;
    // Extract full domain from the email address
    let domain = email.substring(email.lastIndexOf("@")  1);
    // Check if the domain is present in the array of valid domains
    if (domain_list.includes(domain)) {
        window.location.href="singin.html";
        return true;
    } else {
        alert('invalid Email address, please correct')
        return false;
    }
}
  • Related