2010-03-03 222 views
23

任何人都可以幫助我創建密碼驗證的正則表達式。密碼驗證的正則表達式

的條件爲「密碼必須包含8個字符和至少一個數字,一個字母和一個獨特的性格,如!#$%&? "

+0

密碼規則不好。請參閱[參考 - 密碼驗證](https://stackoverflow.com/questions/48345922/reference-password-validation)以獲取更多信息。 – ctwheels

回答

49
^.*(?=.{8,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$ 

--- 

^.*    : Start 
(?=.{8,})  : Length 
(?=.*[a-zA-Z]) : Letters 
(?=.*\d)   : Digits 
(?=.*[!#$%&? "]) : Special characters 
.*$    : End 
+0

+1的解釋 - 測試了幾個例子,並在http://www.regular-expressions.info/javascriptexample.html – amelvin

+0

工作我厭倦了'acf23!&7h',它不驗證它 – Andromeda

+0

不要忘記逃脫必要的字符... – Macmade

5

可以實現每個個性化需求很輕鬆地(例如,最少8個字符:.{8,}將匹配8個或更多字符)

要結合他們,你可以使用「正期待」到多個子表達式都適用於相同的內容喜歡的東西(?=.*\d.*).{8,}匹配一個(或多個)數字與前瞻,和。 8個或更多字符

所以:

 
(?=.*\d.*)(?=.*[a-zA-Z].*)(?=.*[!#\$%&\?].*).{8,} 

記住逃跑元字符。

+1

你有幾個毫無意義的「。*」在那裏。你可以使用:(?=。* \ d)(?=。* [a-zA-Z])(?=。* [!#\ $%&\?])。{8,} –

+0

@TomLord我想測試一下......但你可能是對的(理由:當然,每個積極的前瞻只需要確認每種類型角色的一個實例)。 – Richard

+0

是的,我指出的主要原因是,如果你的正則表達式不匹配,那麼如果你包含不必要的「,那麼確定這個可能會大大地低效。*'s in there! –

7

試試這個

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{6,20}) 

上述正則表達式的說明:

(   # Start of group 
    (?=.*\d)  # must contains one digit from 0-9 
    (?=.*[a-z])  # must contains one lowercase characters 
    (?=.*[\W])  # must contains at least one special character 
       .  #  match anything with previous condition checking 
       {8,20} #  length at least 8 characters and maximum of 20 
)   # End of group 

「/ W」將增加可用於密碼和坑可以更安全的字符範圍。

+0

爲什麼你需要所有的(。*)?似乎工作得很好,如果你只是做了:(?= \ d *)(?= [az] *)(?= [AZ ] *)(?= [\ W] *)。{6,20} –

1

您可以爲javascript驗證制定自己的正則表達式;

 (/^ 
     (?=.*\d)    //should contain at least one digit 
     (?=.*[a-z])    //should contain at least one lower case 
     (?=.*[A-Z])    //should contain at least one upper case 
     [a-zA-Z0-9]{8,}   //should contain at least 8 from the mentioned characters 

     $/) 

實施例: - /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{7,}$/

4

密碼符合下列條件:

  1. 至少1位數
  2. 至少2特殊字符
  3. 至少1字母字符
  4. 沒有空格

    'use strict'; 
    (function() { 
        var foo = '3g^g$'; 
    
        console.log(/^(?=.*\d)(?=(.*\W){2})(?=.*[a-zA-Z])(?!.*\s).{1,15}$/.test(foo)); 
    
        /** 
        * (?=.*\d)   should contain at least 1 digit 
        * (?=(.*\W){2}) should contain at least 2 special characters 
        * (?=.*[a-zA-Z]) should contain at least 1 alphabetic character 
        * (?!.*\s)   should not contain any blank space 
        */ 
    })();