可能重复:
正则表达式匹配整个字符串
在我的表单页面上,我试图让它只接受我的用户名和密码的字母数字字符,并要求它们为 6 到 15 个字符。当我输入无效数据时,它会将其插入数据库,而不是抛出我在 CheckAlNum 函数中定义的用户错误。
函数.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
表单.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
我尝试过使用 checkAlNum 函数的 if-else 语句以及正则表达式的嵌套(尽管我很确定正则表达式是正确的)。也许我只是错过了一些非常愚蠢的东西?