JS学生电子邮件验证

问题描述 投票:0回答:1

我是Java语言的初学者,我正在寻找一种解决方案,以解决下面的代码不起作用的原因。我已经在此处查看了StackOverflow上的一些教程,并认为它应该可以工作……但事实并非如此。

HTML看起来像这样:

<form id="personalInfo"> 
<h2>Email: </h2> <input type="text" name="Email" id="Email">  <br>
</form> 

<input type="button" onclick = "validateEmail()">

JavaScript看起来像这样:

function validateEmail() 
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\@([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms[personalInfo].elements[Email].value;

if (reg.test(address)== false)
{
    alert ("Email not valid");
    return false
}   
return true;
}

通过我的帐户,如果用户输入的电子邮件地址无效,这会弹出一个警报。相反,什么也没有发生。我不确定测试是否可以运行。

javascript email-validation
1个回答
0
投票

function validateEmail() {
  // There are better version online, you can check "https://emailregex.com/"
  var reg = /^([A-Za-z0-9_\-\.]){1,}\@([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
  // document.getElementById() - Easier to read & understand, more widely used
  var address = document.getElementById('Email').value;

  // Corrected your returns - not the main issue in the function, but it helps
  // it make sense I feel
  if (reg.test(address) == false) {
    alert("Email not valid");
    return false
  }
  return true
}
<form id="personalInfo">
  <h2>Email: </h2>
  <input type="text" name="Email" id="Email">
</form>

<input type="button" onclick="validateEmail()">
© www.soinside.com 2019 - 2024. All rights reserved.