简体   繁体   中英

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:

<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:

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:

<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. Try emailError instead of 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;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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