gpt4 book ai didi

javascript - JS 学生电子邮件验证

转载 作者:行者123 更新时间:2023-12-01 00:25:51 24 4
gpt4 key购买 nike

我是 Javascript 初学者,正在寻找以下代码不起作用的解决方案。
我已经在 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;
}

根据我的帐户,如果用户输入的电子邮件地址无效,应该会弹出警报。
相反,什么也没有发生。我不确定测试是否运行。

最佳答案

function validateEmail() {
// There are, I feel, better version of this regex 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, and more widely used
var address = document.getElementById('Email').value;

// Corrected your returns - not the main issue in the function, but the old
// returns might have caused confusion
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>

<!-- You had a typo on the onclick but has since been fixed -->
<input type="button" onclick="validateEmail()" value="Submit">

关于javascript - JS 学生电子邮件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59011328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com