简体   繁体   中英

How can I create a function to validate an email and a username with a Javascript?

I'm very new in coding. I'm creating a newsletter form and I'll need people to register by entering a name (only letters) and a valid email address.I'm trying to create a javascript function but it does not work properly. Function is:

function validaIscrizione(username,email) {

        var nameRegex = /^[a-zA-Z\-]+$/
        var emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

        if(
        username==''|| username==undefined || nameRegex.test(username)||
        email== '' || email == undefined || emailRegex.test(email)
      )
        {return false;}

      else{return true;}  

}




var button = document.getElementById('btn_1');

button.onclick=function(){
  var login=document.getElementById('username').value;
  var password=document.getElementById('email').value;
  var result = document.getElementById('result');

      if(validaIscrizione(username,email)){
result.innerHTML = "Grazie per aver effettuato la registrazione";
      }else{
        result.innerHTML = "Dati non validi";
      }
}

"

am I missing something? Thank you in advance

I modify a little your validate function and put comments with the explanation:

function validaIscrizione(username, email) {
  const nameRegex = /^[a-zA-Z\-]+$/;
  const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

// here you use short circuit for the falsy values like "" or undefined and validate the regex
  const isUsernameValid = username && nameRegex.test(username);
  const isEmailValid = email && emailRegex.test(email);

// here you return that is valid only if the two inputs pass your tests
  return isUsernameValid && isEmailValid;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM