2014-05-03 62 views
0

我在第一次嘗試Javascript內聯表單驗證。我借用了另一個網站的代碼,並做了一切建議,以使其正確,但它仍然無法正常工作。如果信息有誤,它應該將表格框變爲紅色,並在錯誤的框下面打印信息,如果輸入的信息正確,則將其變爲綠色。請幫忙。JavaScript內聯驗證不起作用

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Request Info</title> 
<link href="bnb stylesheet.css" rel="stylesheet" type="text/css" /> 

<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:400,700,800' rel='stylesheet' type='text/css'> 

<style type="text/css"> 

.sidebar1 { 
    float: right; 
    width: 180px; 
    background-color: #9CBEEF; 
    padding-bottom: 10px; 
} 
</style> 

    <script> 
    //Script validation coding borrowed from Philip Brown on Culttt.com 

//culttt.com/2012/08/08/really-simple-inline-javascript-validation/ 

//Validation 

    function validateName(x){ 
     // Validation rule 
     var re = /[A-Za-z -']$/; 
     // Check input 
     if(re.test(document.getElementById(x).value)){ 
     // Style green 
     document.getElementById(x).style.background ='#ccffcc'; 
     // Hide error prompt 
     document.getElementById(x + 'Error').style.display = "none"; 
     return true; 
     }else{ 
     // Style red 
     document.getElementById(x).style.background ='#e35152'; 
     // Show error prompt 
     document.getElementById(x + 'Error').style.display = "block"; 
     return false; 
     } 
    } 

    function validateName(lname){ 
     // Validation rule 
     var re = /[A-Za-z -']$/; 
     // Check input 
     if(re.test(document.getElementById(lname).value)){ 
     // Style green 
     document.getElementById(lname).style.background ='#ccffcc'; 
     // Hide error prompt 
     document.getElementById(lname + 'Error').style.display = "none"; 
     return true; 
     }else{ 
     // Style red 
     document.getElementById(lname).style.background ='#e35152'; 
     // Show error prompt 
     document.getElementById(lname + 'Error').style.display = "block"; 
     return false; 
     } 
    } 

    // Validate email 
    function validateEmail(email){ 
     var re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
     if(re.test(document.getElementById(email).value)){ 
     document.getElementById('email').style.background ='#ccffcc'; 
     document.getElementById('emailError').style.display = "none"; 
     return true; 
     }else{ 
     document.getElementById('email').style.background ='#e35152'; 
     return false; 
     } 
    } 

//Validate phone  
     function validatePhone(phone){ 
     // Validation rule 
     var re = /[0-9-']$/; 
     // Check input 
     if(re.test(document.getElementById(phone).value)){ 
     // Style green 
     document.getElementById(phone).style.background ='#ccffcc'; 

     //Validate Comments 
      function validateComment(x){ 
     // Validation rule 
     var re = /[A-Za-z -']$/; 
     // Check input 
     if(re.test(document.getElementById(comment).value)){ 
     // Style green 
     document.getElementById(comment).style.background ='#ccffcc'; 
     // Hide error prompt 
     document.getElementById(x + 'Error').style.display = "none"; 
     return true; 
     }else{ 
     // Style red 
     document.getElementById(x).style.background ='#e35152'; 
     // Show error prompt 
     document.getElementById(x + 'Error').style.display = "block"; 
     return false; 
     } 
    } 
     // Hide error prompt 
     document.getElementById(x + 'Error').style.display = "none"; 
     return true; 
     }else{ 
     // Style red 
     document.getElementById(x).style.background ='#e35152'; 
     // Show error prompt 
     document.getElementById(x + 'Error').style.display = "block"; 
     return false; 
     } 
    } 
    // Validate Select boxes 
    function validateCheckbox(terms){ 
     if(document.getElementById(terms).checked){ 
     return true; 
     } 
     return false; 
    } 
    function validateForm(){ 
     // Set error catcher 
     var error = 0; 
     // Check name 
     if(!validateName('name')){ 
     document.getElementById('nameError').style.display = "block"; 
     error++; 
     } 

     //Validate last name 
     if(!validateName('lname')){ 
     document.getElementById('nameError').style.display = "block"; 
     error++; 
     } 

     //Validate phone 
     if(!validatePhone('phone')){ 
     document.getElementById('phoneError').style.display = "block"; 
     error++; 
     } 
     // Validate email 
     if(!validateEmail(document.getElementById('email').value)){ 
     document.getElementById('emailError').style.display = "block"; 
     error++; 
     } 

    //Validate message 
    if(!validateComment('comment')){ 
     document.getElementById('commentError').style.display = "block"; 
     error++; 
     } 

//Validate Checkbox 
     if(!validateCheckbox('terms')){ 
     document.getElementById('termsError').style.display = "block"; 
     error++; 
     } 
     // Don't submit form if there are errors 
     if(error > 0){ 
     return false; 
     } 
    }  
    </script> 


</head> 

<body> 

<div class="container"> 
    <div class="header"><a href="Request Info.html"><img src="images/logo 3.png" alt="Insert Logo Here" name="Insert_logo" width="980" height="200" id="Insert_logo" style="background-color: #9cbeef; display:block;" /></a> 
    </div> 

    <div id="navcontainer"> 
<ul id="navlist1"> 
<li id="active1"><a href="Home.html" id="current">Home</a></li> 
<li><a href="Host Services.html">Host</a></li> 
<li><a href="Guest Services.html">Guest</a></li> 
<li><a href="About Us.html">About Us</a></li> 
<li><a href="Request Info.html">Request Info</a></li> 
</ul> 
</div> </div> 


    <div class="content"> 
    <div class="content"> 
     <h1>Contact</h1> 
    <form action="Request Info2.html" onsubmit="return validateForm()" method="post"> 

    <fieldset> 
    <legend>Required Information</legend> 
<table cellpadding="3"> 

     <tr><td><label for="name"><strong>First Name:</strong></label></td><td> 
     <input type="text" name="name" id="name" maxlength="30" onblur="validateName(name)" placeholder="Johnny"/> 
     <span id="fnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr> 

     <tr><td><label for="lname"><strong>Last Name:</strong></label></td><td> 
     <input type="text" name="lname" id="lname" maxlength="30" onblur="validateName(lname)" placeholder="Smith"/> 
     <span id="lnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr> 

     <tr><td><label for="email"><strong>Email:</strong></label></td><td> 
     <input type="text" name="email" id="email" maxlength="75" onblur="validateEmail(email)" placeholder="[email protected]"/> 
     <span id="emailError" style="display: none;">You can must enter a valid email address</span></td></tr> 

     <tr><td><label for="phone"><strong>Phone:</strong></label></td><td> 

     <input type="text" name="phone" id="phone" maxlength="11" onblur="validatePhone(phone)" placeholder="303-777-7777"/> 
     <span id="phoneError" style="display: none;">You can only use numbers</span></td></tr> 

    <tr><td><strong><label for="comment">Comments:</strong></label> 
     </td><td> 
<textarea input type="text" name="comment" id="comment" textarea rows="10" cols="30"maxlength="500" > 
</textarea> 
     <span class="validateComment" id="commentError" style="display: none;">Please leave us your comments</span></td></tr> 
     </table> 
    </fieldset> 


    <fieldset style="text-align: center" > 
     <label ="terms"><strong>Terms and Conditions</strong></label><br> 

     <p>Please read our <a href="Privacy.html">Privacy Policy </a>before submitting. We will always protect your privacy. You have the ability to change, update or terminate your information on the site at anytime you choose. B-n-B Concierges also reserves the right to remove any person from the site at their discretion. </p> 
    <br/> 
    I confirm that I agree with terms & conditions 

      <input type="checkbox" name="terms" id="accept" value="accept" maxlength="10" onblur="validateCheckbox(terms)" /> 
<span class="validateError" id="termsError" style="display: none;">You need to accept our terms and conditions</span> 
    </fieldset> 
    <fieldset> 
     <input type="submit" id="submit" name="submit" value="Submit" /> 
    </fieldset> 
    </form> 
    </div> 
</div> 
    <div class="footer"> 
    <p><div id="navcontainer"> 
<ul id="navlist2"> 
<li id="active2"><a href="Policies.html" >Conditions</a></li> 
<li><a href="Privacy.html">Privacy</a></li> 
<li><a href="Registration.html">Sign Up</a></li> 
<li><a href="#">© 2014 Heidi Medina</a></li> 
</ul> 
</div> 
</div> 
</body> 
</html> 
+1

爲什麼你有2個函數'validateName'定義? –

+0

爲什麼不嘗試讓jquery驗證插件試試? http://jqueryvalidation.org/documentation/ –

+0

錯過了U_Mulder,我會糾正這一點。至於JQuery的問題。這個爛攤子是一個分配的學校,必須以某種方式完成,這是做事的一種更難的方式。所以目前我必須這樣做,不能使用JQuery的更簡單的方法。 – user3446663

回答

0

@ user3446663:

以下代碼有效。請注意,我已將表單操作屬性留空,因爲您所引用表單的名稱中有空格(請求Info2.html)。您需要將該下劃線放在該文件名中,以便讀取「Request_Info2.html」或刪除空格,以便讀取「RequestInfo2.html」以便正確識別文件名。這裏的代碼:

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Request Info</title> 

    <link href="bnb stylesheet.css" rel="stylesheet" type="text/css" /> 
    <link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:400,700,800' rel='stylesheet' type='text/css'> 

    <style type="text/css"> 

    .sidebar1 { 
     float: right; 
     width: 180px; 
     background-color: #9CBEEF; 
     padding-bottom: 10px; 
    } 
    </style> 

    <script> 
     //Script validation coding borrowed from Philip Brown on Culttt.com 
     //culttt.com/2012/08/08/really-simple-inline-javascript-validation/ 

     // Validate first/last name 
     function validateName(name){ 

      // Validation rule 
      var re = /[A-Za-z -']$/; 

      // Check input 
      if (re.test(document.getElementById(name).value)){ 

       // Style green 
       document.getElementById(name).style.background ='#ccffcc'; 

       // Hide error prompt 
       document.getElementById(name + 'Error').style.display = "none"; 

       return true; 

      } else { 

       // Style red 
       document.getElementById(name).style.background ='#e35152'; 

       // Show error prompt 
       document.getElementById(name + 'Error').style.display = "block"; 

       return false; 
      } 
     } 

     // Validate email 
     function validateEmail(email){ 
      var re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
      if (re.test(document.getElementById(email).value)){ 
       document.getElementById(email).style.background ='#ccffcc'; 
       document.getElementById(email + 'Error').style.display = "none"; 
       return true; 
      } else { 
       document.getElementById(email).style.background ='#e35152'; 
       document.getElementById(email + 'Error').style.display = "block"; 
       return false; 
      } 
     } 

     //Validate Comments 
     function validateComment(comment){  
      var re = /[A-Za-z -']$/; 
      if (re.test(document.getElementById(comment).value)){ 
       document.getElementById(comment).style.background ='#ccffcc'; 
       document.getElementById(comment + 'Error').style.display = "none"; 
       return true; 
      } else { 
       document.getElementById(comment).style.background ='#e35152'; 
       document.getElementById(comment + 'Error').style.display = "block"; 
       return false; 
      } 
     } 

     //Validate phone  
     function validatePhone(phone){  
      var re = /[0-9-']$/;   
      if(re.test(document.getElementById(phone).value)){  
       document.getElementById(phone).style.background ='#ccffcc';  
       document.getElementById(phone + 'Error').style.display = "none"; 
       return true; 
      } else {   
       document.getElementById(phone).style.background ='#e35152';  
       document.getElementById(phone + 'Error').style.display = "block"; 
       return false; 
      } 
     } 

     // Validate checkbox 
     function validateCheckbox(terms){ 
      if(document.getElementById(terms).checked){ 
       document.getElementById(terms + 'Error').style.display = "none"; 
       return true; 
      } else {     
       document.getElementById(terms + 'Error').style.display = "block"; 
       return false; 
      } 
     } 

     // Validate Form 
     function validateForm(){    

      // Set error catcher 
      var error = 0; 

      // Validate first name 
      if (!validateName('fname')){ 
       document.getElementById('fnameError').style.display = "block"; 
       error++; 
      } 

      //Validate last name 
      if (!validateName('lname')){ 
       document.getElementById('lnameError').style.display = "block"; 
       error++; 
      } 

      //Validate phone 
      if (!validatePhone('phone')){ 
       document.getElementById('phoneError').style.display = "block"; 
       error++; 
      } 
      // Validate email 
      if (!validateEmail('email')){ 
       document.getElementById('emailError').style.display = "block"; 
       error++; 
      } 

      //Validate message 
      if (!validateComment('comment')){ 
       document.getElementById('commentError').style.display = "block"; 
       error++; 
      } 

      //Validate checkbox 
      if (!validateCheckbox('terms')){ 
       document.getElementById('termsError').style.display = "block"; 
       error++; 
      } 

      // Don't submit form if there are errors 
      if (error > 0){ 
       return false; 
      } 

     }  
    </script> 

</head> 

<body> 
    <div class="container"> 
     <div class="header"> 
      <a href="Request Info.html"> 
       <img src="images/logo 3.png" alt="Insert Logo Here" name="Insert_logo" width="980" height="200" id="Insert_logo" style="background-color: #9cbeef; display:block;" /> 
      </a> 
     </div> 

     <div id="navcontainer"> 
      <ul id="navlist1"> 
       <li id="active1"><a href="Home.html" id="current">Home</a></li> 
       <li><a href="Host Services.html">Host</a></li> 
       <li><a href="Guest Services.html">Guest</a></li> 
       <li><a href="About Us.html">About Us</a></li> 
       <li><a href="Request Info.html">Request Info</a></li> 
      </ul> 
     </div> 
    </div> 

    <div class="content"> 

     <h1>Contact</h1> 

     <form action="" onsubmit="return validateForm()" method="post"> 
      <fieldset> 
       <legend>Required Information</legend> 
       <table cellpadding="3"> 
        <tr><td><label for="name"><strong>First Name:</strong></label></td><td> 
        <input type="text" name="fname" id="fname" maxlength="30" onblur="validateName(name)" placeholder="Johnny"/> 
        <span id="fnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr> 

        <tr><td><label for="lname"><strong>Last Name:</strong></label></td><td> 
        <input type="text" name="lname" id="lname" maxlength="30" onblur="validateName(name)" placeholder="Smith"/> 
        <span id="lnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr> 

        <tr><td><label for="email"><strong>Email:</strong></label></td><td> 
        <input type="text" name="email" id="email" maxlength="75" onblur="validateEmail(name)" placeholder="[email protected]"/> 
        <span id="emailError" style="display: none;">You can must enter a valid email address</span></td></tr> 

        <tr><td><label for="phone"><strong>Phone:</strong></label></td><td> 
        <input type="text" name="phone" id="phone" maxlength="11" onblur="validatePhone(name)" placeholder="303-777-7777"/> 
        <span id="phoneError" style="display: none;">You can only use numbers</span></td></tr> 

        <tr><td><strong><label for="comment">Comments:</strong></label></td><td> 
        <textarea input type="text" name="comment" id="comment" textarea rows="10" cols="30"maxlength="500" onblur="validateComment(name)" ></textarea> 
        <span class="validateComment" id="commentError" style="display: none;">Please leave us your comments</span></td></tr> 
       </table> 
      </fieldset> 

      <fieldset style="text-align: center" > 
       <label ="terms"><strong>Terms and Conditions</strong></label><br> 
       <p>Please read our <a href="Privacy.html">Privacy Policy </a>before submitting. We will always protect your privacy. 
        You have the ability to change, update or terminate your information on the site at anytime you choose. B-n-B 
        Concierges also reserves the right to remove any person from the site at their discretion.</p><br/> 
        I confirm that I agree with terms & conditions 

       <input type="checkbox" name="terms" id="terms" value="accept" maxlength="10" onblur="validateCheckbox(name)" /> 
       <span class="validateError" id="termsError" style="display: none;">You need to accept our terms and conditions</span> 
      </fieldset> 

      <fieldset> 
       <input type="submit" id="submit" name="submit" value="Submit" /> 
      </fieldset> 
     </form> 

    </div> 

    <div class="footer"> 
     <div id="navcontainer"> 
      <ul id="navlist2"> 
       <li id="active2"><a href="Policies.html" >Conditions</a></li> 
       <li><a href="Privacy.html">Privacy</a></li> 
       <li><a href="Registration.html">Sign Up</a></li> 
       <li><a href="#">© 2014 Heidi Medina</a></li> 
      </ul> 
     </div> 
    </div> 
</body> 
</html> 
+0

非常感謝Trevor。有效!我一直在盯着那個代碼3天試圖找到錯誤。再次感謝。 – user3446663

+0

不客氣!比較你之前使用新代碼的內容會告訴你你可能出錯的地方。很高興我能幫上忙。 – trevor

0

我不相信這是值得回答的,但我還沒有足夠的聲望來評論到目前爲止。

如果可能,請考慮使用HTML5模式。

例子
http://html5pattern.com/Names

填充工具
https://github.com/ryanseddon/H5F

大多數簡單地指定輸入類型的時間足夠(電話,電子郵件)
<input type="email" name="" value="" required />

的需要,可 - 使用模式屬性
調整驗證<input type="text" pattern="[a-zA-Z0-9]+">

+0

感謝您的鏈接,我可以看到那些幫助。 – user3446663

0

代碼中有幾個小問題。 您的JS代碼中錯誤地提供了ID值

例如:您有fnameError作爲ID以在名字中顯示錯誤。

<span id="fnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span> 

而在JavaScript中,你使用了剛剛nameError

document.getElementById('nameError').style.display = "block"; 

相似類型的拼寫問題是有沒有姓也..修復如果有引用了因拼寫差異問題,那麼你很好去。

+0

感謝Rahul :) – user3446663