2013-05-01 79 views
0

我已經開始爲用戶註冊編寫驗證。這種形式使用戶可以在網站上註冊,但是我在如何正確編寫每個字段的驗證方面存在問題。用戶註冊 - 驗證和存儲

至今:

<div id="content"> 
     <div class="ic"></div> 
     <div class="inner"> 
      <div class="container_12"> 
       <div class="wrapper"> 
        <div class="grid_12"> 
        </div> 
       </div> 
       <div class="wrapper"> 
        <div class="grid_12"> 
         <h2 class="h-pad1">Open an Account with Us</h2> 
         <form action="" id="validate" class="form" method="POST"> 
      <fieldset> 
       <div class="formRow"> 
        <label for="login">Username:</label> 
        <div class="loginInput"><input type="text" name="username" class="validate[required]" id="username" maxlength="15"/></div> 
        <div class="clear"></div> 
       </div> 

       <div class="formRow"> 
        <label for="pass">Password:</label> 
        <div class="loginInput"><input type="password" name="password" class="validate[required]" id="pass" /></div> 
        <div class="clear"></div> 
       </div> 

       <div class="formRow"> 
        <label for="pass">Repeat Password:</label> 
        <div class="loginInput"><input type="password" name="rpassword" class="validate[required]" id="rpass" /></div> 
        <div class="clear"></div> 
       </div> 

       <div class="formRow"> 
        <label for="pass">Email:</label> 
        <div class="loginInput"><input type="text" name="email" class="validate[required]" id="email" /></div> 
        <div class="clear"></div> 
       </div> 

什麼是正確的代碼添加?謝謝。

回答

1

你的最重要的任務是學習如何使用document.getElementById()如果你打算使用常規的JavaScript。使用該功能,您可以獲取不同字段中的值並檢查存儲在其中的內容。

我會有一個高級功能validateRegistrationForm()調用函數驗證每個字段。例如

function validateRegistrationForm(){ 
    if(!validateEmailField()) // Invalid email format 
      return; 
    if(!validatePasswordField()) // Invalid password length 
      return; 
    if(validateUserNameField()) // invalide characters in email 
      return; 
    . 
    . 
    etc. 
} 

function validateEmailField(){ 
    var x=document.getElementById("email").value; 
    var atpos=x.indexOf("@"); 
    var dotpos=x.lastIndexOf("."); 
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) 
    { 
     errorPopup("Not a valid e-mail address"); 
     return false; 
    } 

    if(email==x) //If the old email is equal to the current then perform no check for uniqueness. On the server side the email portion will be ignored. 
     return true; 

    return isEmailUnique(); // return true if the email is unique 
} 
+0

質量的答案,謝謝。 – user2338118 2013-05-01 06:30:28

0

你可以有這樣的事情:

function validate() 
{ 

var uName = document.getElementById('username'); 

if(uName == '' or uName=' ') 
{ 

// do something 

} 

repeat for other elements. 

. 
. 
. 
. 

// in the end, you can return true; if all validation condition meet or else return false; 

}