如何检查用户输入的密码格式。字符串不重复,使用用户必须选择数字、字符串(小写/大写)
听到是我的代码。我在 preg_match 中的问题是什么?
function checkPassFormat($ip)
{
if(preg_match('/^[a-A][0-9]/', $password))
return TRUE;
else
return FALSE;
}
如何检查用户输入的密码格式。字符串不重复,使用用户必须选择数字、字符串(小写/大写)
听到是我的代码。我在 preg_match 中的问题是什么?
function checkPassFormat($ip)
{
if(preg_match('/^[a-A][0-9]/', $password))
return TRUE;
else
return FALSE;
}
I think this is a cute solution for the issue (you can also collect the errors and show the user a friendly message):
const SECURELEVEL_LOW = 1;
const SECURELEVEL_MEDIUM = 2;
const SECURELEVEL_HIGH = 3;
const SECURELEVEL_SERVICE = 4;
const CONTAINS_LETTERS = 1;
const CONTAINS_DIGITS = 2;
const CONTAINS_CASESENSITIVELETTERS = 4;
const CONTAINS_SPECIALCHARS = 8;
public function _isValid($value) {
$valid = true;
switch ($this->_options['secureLevel']) {
case self::SECURELEVEL_SERVICE:
$minLength = 20;
$hasToContain = self::CONTAINS_LETTERS + self::CONTAINS_DIGITS + self::CONTAINS_CASESENSITIVELETTERS + self::CONTAINS_SPECIALCHARS;
break;
case self::SECURELEVEL_HIGH:
$minLength = 8;
$hasToContain = self::CONTAINS_LETTERS + self::CONTAINS_DIGITS + self::CONTAINS_CASESENSITIVELETTERS;
break;
case self::SECURELEVEL_LOW:
$minLength = 4;
$hasToContain = 0;
break;
case self::SECURELEVEL_MEDIUM:
default:
$minLength = 5;
$hasToContain = self::CONTAINS_LETTERS + self::CONTAINS_DIGITS;
break;
}
if (strlen($value) < $minLength) {
$valid = false;
}
if (strpos($value, ' ') !== false) {
$valid = false;
}
if ($hasToContain & self::CONTAINS_LETTERS) {
// Password has to contain letters
if (!preg_match('/[a-z]/i', $value)) {
$valid = false;
}
}
if ($hasToContain & self::CONTAINS_DIGITS) {
// Password has to contain numbers
if (!preg_match('/[0-9]/', $value)) {
$valid = false;
}
}
if ($hasToContain & self::CONTAINS_CASESENSITIVELETTERS) {
// Password has to contain small and capital letters
if (!preg_match('/[a-z]/', $value) || !preg_match('/[A-Z]/', $value)) {
$valid = false;
}
}
if ($hasToContain & self::CONTAINS_SPECIALCHARS) {
// Password has to contain a special character
if (!preg_match('/[^0-9a-zA-Z]/', $value)) {
$valid = false;
}
}
return $valid;
}
我认为这[a-A]
意味着您只允许 small 和 capital A
。这应该是[a-zA-Z]
。您也可以尝试[a-Z]
,但在 C# 中,例如这不能按预期工作。
此外,您可能需要说“多个字母后跟多个数字”:[a-zA-Z]+[0-9]+
。这将允许像abDCkl98
.
如果你想混合字母和数字,你应该做类似的事情[a-zA-Z0-9]+
。这适用于像a9Bdc4re
.
尝试这个:
preg_match("/^[a-zA-Z0-9]+$/", $password)
按照您的示例,这是另一种选择:
"/[:alpha:][:digit:]/"
试试这个 $pattern = "/^[a-zA-Z0-9]*$/i"; if(preg_match($pattern, $value)){ 返回真; }别的{ 返回假; }