这是我的代码:
<form method="post" name="form1" action="invitation_enrollv5.asp?action=1" onSubmit="return GetTextValue()">
<input style="float:right;" id="nextbutton" name="" type="submit" value="Next" />
</form>
我可以知道,我如何以及在哪里添加验证脚本来验证输入电子邮件地址。
如果我空白或无效的ID意味着它显示错误状态。
任何人都可以帮助我吗?提前谢谢。
答案 0 :(得分:1)
对于输入框,您可以将类型指定为电子邮件,浏览器将为您验证。
<input type="email" required>
或者对于javascript:
function validate(emailString) {
return /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(emailString)
}
如果emailString参数的值是有效的电子邮件,则返回true。
答案 1 :(得分:0)
让我们假设你的HTML中有一个输入字段 -
<form name="emailForm">
<input type="email" id="email" name="email" />
</form>
在您的javascript中,您可以在用户激活时添加事件处理程序 文本字段,然后单击其他位置(或使用选项卡导航到下一个字段)
$('#email').blur(function() {
// Instead of .blur() you can also just have the
// form submit event use the checkEmail() function.
checkEmail();
});
function checkEmail(){
var email = document.forms["emailForm"]["email"].value;
var atnum = email.replace(/[^@]/g, '').length
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || email.length <= dotpos + 2 || atnum > 1) {
// E-mail was not valid
$('#email').css({border: '1px solid #e74c3c'});
alert("Not a valid e-mail address");
setTimeout( function() {
$('#email').css({border: '1px solid #555'});
}, 800);
} else {
// E-mail was OK
alert("You're good to go!");
}
}
这是fiddle