显示Javascript表单验证消息

时间:2013-11-30 16:37:21

标签: javascript forms validation

所以我有一个简单的表单,如果没有正确输入字段,我希望它显示一条消息警告,到目前为止,我有一个运行良好的示例并显示警告信息:

function validateName(x){
var re = /^[a-z ,.'-]+$/i;
if(re.test(document.getElementById(x).value)){
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false; 
}
}

以下是全名字段的html:

<p  class="ex"><strong>Full Name:</strong>
 <br>
 <input type="text" name="name" placeholder="First Name" id="name" onblur="validateName(name)">
 <span id="nameError" style="display: none;">Only alphabetic characters, hyphens & apostrophes are accepted.</span>

现在,我想对电子邮件字段执行相同操作,如果输入错误,则会将框显示为红色,但不会显示任何消息。继承了我到目前为止的Javascript:

function validateEmail(email){ 
var re = /^(([^<>()[\]\\.,;:\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(re.test(email)){
document.getElementById('email').style.background ='#ccffcc';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.background ='#e35152';
document.getElementById(email + 'Error').style.display = "block";
return false;
}
}

下面是电子邮件字段的html:

<strong>Contact Email:</strong>
<br>
<input type="text" name="email" placeholder="Example@Email.com" id="email" onblur="validateEmail(value)" />
<span id="emailError" style="display: none;">You must enter a valid email address</span>

1 个答案:

答案 0 :(得分:0)

您将错误的ID传递给元素选择器。 请尝试使用emailError代替email+'Error'

function validateEmail(email){ 
var re = /^(([^<>()[\]\\.,;:\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(re.test(email)){
document.getElementById('email').style.background ='#ccffcc';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.background ='#e35152';
document.getElementById('emailError').style.display = "block";
return false;
}
}