[英]Use regular expressions to validate passwords
我有一個應符合以下條件的密碼字段
另外,我想知道所有語言的正則表達式是否相同?
鏈接到開始使用正則表達式的好教程(假設我只有基本的理解)也很好。
謝謝
最小值和最大值只使用strlen
。
我會使用一個字符和一個數字preg_match
:
$len = strlen($string);
if ($len < 5) {
// too short
}elseif ( $len > 20) {
// too long.
}elseif (!preg_match('#[0-9]#', $string)) {
// does not contain a digit
}elseif (!preg_match('#[a-z]#i', $string)) {
// does not have a character
}
我喜歡將我的檢查拆分為多個檢查,這樣我就可以准確地告訴用戶缺少什么。 有些人更喜歡將它捆綁在一起。
正則表達式是一個非常好的密碼驗證工具。 可以使用從字符串開頭應用的前瞻斷言(使用AND
邏輯)來應用多個規則,如下所示:
$re = '/
# Match password with 5-20 chars with letters and digits
^ # Anchor to start of string.
(?=.*?[A-Za-z]) # Assert there is at least one letter, AND
(?=.*?[0-9]) # Assert there is at least one digit, AND
(?=.{5,20}\z) # Assert the length is from 5 to 20 chars.
/x';
if (preg_match($re, $text)) {
// Good password
}
這是等效的 Javascript:
var re = /^(?=.*?[A-Za-z])(?=.*?[0-9])(?=.{5,20}$)/;
if (re.test(text)) {
// Good password
}
一篇關於使用 regex 進行密碼驗證的好文章是: Password Strength Validation with Regular Expressions 。 (雖然他的最后表達在開頭包括一個錯誤的點星 - 請參閱我在他的博客上的評論)。
另請注意,正則表達式語法確實因語言而異(但大多數都融合在 Perl 語法上)。 如果您真的想了解正則表達式(在 Neo 中: “我知道 Kung-Fu”的意思),那么沒有比坐下來閱讀: Mastering Regular Expressions(第 3 版)作者 Jeffrey Friedl 更好的方法了。
附加:可以提出一個很好的論點,即密碼驗證應該分成多個測試,這允許代碼為每種類型的驗證錯誤提供特定的錯誤消息。 此處提供的答案旨在演示一種僅使用一個正則表達式驗證多個規則的正確方法。
快樂的正則表達式!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.