2012-08-04 58 views
0

我在我的註冊表單中有一個密碼字段。以下是javascript驗證的代碼。單引號的javascript驗證

if(document.getElementById('txtPassword').value == '' || document.getElementById('txtPassword').value == 'Password'){ 
      alert("Please enter Password"); 
      document.getElementById('txtPassword').focus(); 
      return false; 
     } 


     else if (document.getElementById('txtPassword').value.length < 8) 
     { 
       alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number'); 
       return false; 
     } 


     else if ((! document.getElementById('txtPassword').value.match(/[a-z]/)) || (! document.getElementById('txtPassword').value.match(/[A-Z]/))) { 
       alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number'); 
       return false; 
     } 


     else if (!document.getElementById('txtPassword').value.match(/\d+/)) { 
       alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number'); 
       return false; 
     } 

     else if (document.getElementById('txtPassword').length < 8) 
     { 
       alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number'); 
       return false; 
     } 

我需要檢查單引號。如果用戶在密碼字段中輸入單引號,並彈出輸入錯誤「避免在此字段中使用單引號」。

如何做到這一點?

+0

而不是仰視元素及其在每個'if'聲明價值,只是做一次之初並將其存儲在一個變量。 – 2012-08-04 09:32:43

+0

[如何判斷一個字符串是否包含javascript中的某個字符?]的可能重複(http://stackoverflow.com/questions/4444477/how-to-tell-if-a-string-contains-a-certain-字符在JavaScript) – 2012-08-04 09:33:28

回答

4
else if (document.getElementById('txtPassword').value.indexOf("'") != -1) { 
    alert("Avoid single quotes in this field"); 
    return false; 
} 

這裏是一個簡單的測試用例。如果你把一個HTML頁面,把這個頭標記,在瀏覽器中打開它,你會看到它的工作原理:

var value1 = "abc'def"; 
var value2 = "abcdef"; 
if(value1.indexOf("'") != -1) 
    alert(value1 + " contains a '"); 
else 
    alert(value1 + " does not contain a '"); 
if(value2.indexOf("'") != -1) 
    alert(value2 + " contains a '"); 
else 
    alert(value2 + " does not contain a '"); 
+0

它不適合我。 – designersvsoft 2012-08-04 09:33:22

+0

我做了一個編輯,請再試一次。 – Tom 2012-08-04 09:34:09

+0

你做到了。謝謝。 – designersvsoft 2012-08-04 09:39:43

1

使用此正則表達式的密碼校驗

^(?=.*\d)(?=.*[a-zA-Z]).{8,} 

目前你進行大量的驗證檢查,以避免那些只使用上面的正則表達式。

if (! /^(?=.*\d)(?=.*[a-zA-Z]).{8,}/.test(txtPass)) { 
    flag = false; 
} 
else if(txtPass.indexOf("'") != -1) { 
    flag = false; 
} 

if (!flag) 
    alert("Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number"); 

參考LIVE DEMO

+0

感謝您的努力。它正在工作。 – designersvsoft 2012-08-04 09:53:39