简体   繁体   English

显示Javascript表单验证消息

[英]Displaying Javascript form validation message

So I have a simple form and I want it to display a message warning if a field isnt entered correctly, so far I have an example which works well and displays the warning message fine: 因此,我有一个简单的表单,如果没有正确输入字段,我希望它显示一条消息警告,到目前为止,我有一个很好的示例,可以很好地显示警告消息:

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; 
}
}

And heres the html for the Full Name field: 这是全名字段的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>

Now, I want to do the same for the email field, it displays the box as red if entered incorrectly, however no message is shown. 现在,我想对电子邮件字段执行相同的操作,如果输入不正确,它将显示为红色,但是未显示任何消息。 Heres the Javascript I have so far: 到目前为止,这里是我的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;
}
}

Heres the html for the email field: 这是电子邮件字段的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>

You are passing the wrong id to the element selector. 您将错误的ID传递给元素选择器。 Try emailError instead of email+'Error' 尝试用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;
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM