如果电子邮件地址输入错误,我希望向用户显示一条消息。
HTML
<p>Email: <input type="email" id="email" onblur="validateEmail()"
required>
<p id="emailMessage"></p>
JavaScript
function validateEmail(email){
var regEx = /\S+@\S+/;
var result = regEX.test(email);
if (result = true)
document.getElementById("emailMessage").innerhtml = ""
else (result = false)
document.getElementById("emailMessage").innerhtml = "Please enter a valid
email address"
}
答案 0 :(得分:0)
您的方法有很多问题。因为您似乎对此并不陌生,所以我将逐步告诉您什么地方不对:
result = true
和result = false
会将result的值设置为布尔值。条件必须为==
或===
。或者,您可以使用result
变量,由于.test()
的结果,该变量已经是布尔值。innerHTML
代替innerhtml
。regEx
而不是regEX
。email
默认不是该函数的参数,您需要将this
传递给该函数以使其可用。email.value
,仅检查email
,因为这只是元素。else
不需要检查条件,是否需要使用else if
,但此处并不需要。
function validateEmail(email) {
var regEx = /\S+@\S+/;
var result = regEx.test(email.value);
if (result) {
document.getElementById("emailMessage").innerHTML = "";
}
else {
document.getElementById("emailMessage").innerHTML = "Please enter a valid email address";
}
}
<p>Email:</p>
<input type="email" id="email" onblur="validateEmail(this)" required>
<p id="emailMessage"></p>
答案 1 :(得分:-2)
//correct code
function validateEmail(email)
{
var regEx = /\S+@\S+/;
var result = regEX.test(email);
if (result == true)
document.getElementById("emailMessage").innerHTML = ""
else (result == false)
document.getElementById("emailMessage").innerHTML = "Please enter a valid email address"
}
答案 2 :(得分:-3)
document.getElementById("emailMessage").innerHTML = "Please enter a valid
email address"
///使用innerHTML而不是innerhtml,就是问题