[英]password validation using javascript
我需要使用javascript匹配密碼字段,並滿足以下要求:
我有一個正則表達式
var password = / ^(?=。 [0-9])(?=。 [!@#$%^& ])[a-zA-Z0-9!@#$%^& ] {10,20} $ /; 我怎么能解決這個問題?
這可能是必需的正則表達式
^(?=.*[!@#$%^&])(?!.*(.).*\1.*\1)[A-Za-z\d!@#$%^&|]{10,20}$
(?=.*[!@#$%^&])
確保至少出現一次列出的字符。
(?!.*(.).*\\1.*\\1)
確保沒有字符重復兩次以上。
[A-Za-z\\d!@#$%^&|]{10,20}
匹配字符類中10-20次出現的字符。
我會編寫單獨的規則(可能使用所有這些規則的正則表達式 - 為了一致性 - 除非性能是一個很大的問題),每個規則都直接與列表中的規則相關。
var pw = "asddfak@kjg";
/* Should be alpha numaric with at least one special character. */
console.log(null !== pw.match(/[@+#$]/));
/* no spaces to be allowed */
console.log(null !== pw.match(/^\S+$/));
/* should be minimum 10 char and max 20 chars. */
console.log(null !== pw.match(/^.{10,20}$/));
/* No repeate of char more than 2 times. */
console.log(null === pw.match(/(.)(.*\1){2}/));
/* ~,'.:;^| are not allowed */
console.log(null !== pw.match(/^[^~,'.:;^|]+$/));
盡管可以使正則表達式更簡潔,但我認為使規則更符合您的意圖更加可維護。 如果性能是一個重要的問題(通常不是這種事情)那么我會避免正則表達式,並使用字符串方法實現規則。
/ // start regex pattern
[ // open character class
@+#$ // match one of these `special` characters
] // close character class
/ // end regex pattern
/ // start regex pattern
^ // start matched string
\S+ // one or more (`+`) not spaces (`\S`)
$ // end matched string
/ // end regex pattern
/ // start regex pattern
^ // start matched string
.{10,20} // between 10 and 20 of any character (`.`)
$ // end matched string
/ // end regex pattern
/ // start regex pattern
(.) // any character captured as group 1
(.*\1){2} // followed by zero or more of anything (`\.*`) and then the captured group 1 (`\1`) two times (`{2}`)
/ // end regex pattern
/ // start regex pattern
^ // start matched string
[ // open character class
^~,'.:;^| // not (`^`) one of these characters
]+ // close character class
$ // end matched string
/ // end regex pattern
ps你應該用你使用的正則表達式留下很多評論,因為與書不同,它們比閱讀更容易
這應該工作:
/^(?=.*?[!@#$%^&])(?:([a-zA-Z0-9!@#$%^&])(?!.*?\1.*?\1)){10,20}$/
(如果重復超過2次,則表示同一個角色不能出現三次)
說明:
第一個條件 :在一開始,我們將第一次經歷整個字符串,直到我們找到一個特殊字符,一旦我們擁有它,我們停止,如果我們不這樣做,它就會失敗( 來源 ):( (?=.*?[!@#$%^&])
第二個條件 :無事可做, [a-zA-Z0-9!@#$%^&]
不允許空格
第三個條件 :量詞: {10,20}
第四個條件 :微妙的一個:當我們通過字符串時,對於捕獲的每個字符,我們檢查它不再重復兩次(相同的來源): (?!.*?\\1.*?\\1)
第五個條件 :與空格相同
根據您的要求中的5件事情,這是您需要的確切模式
^(?=.*[!@#$%^&])(?!.*(.).*\1.*\1)[^\s~,'.:;^|]{10,20}$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.