在PHP中使用正则表达式进行验证存在一些问题。 (这是课堂上的任务,所以不要在如何做到这一点上有很大的灵活性,只需要让它工作)
switch ($name) {
case 'firstname' :
if (!preg_match('/^[a-zA-Z]+$/', $firstname)) {
$fnameError = "Please enter your first name. ";
$somethingsWrong = true;
} else if (empty($firstname)) {
$fnameError = "Please enter your first name. ";
$somethingsWrong = true;
}
^^这里正则表达式不起作用(任何东西都通过验证)
case 'zip' :
if (!preg_match('/^\d{5}$/', $zip)) {
$zipError = "Standard 5-digit zip codes only. ";
$somethingsWrong = true;
} else if (empty($zip)) {
$zipError = "Standard 5-digit zip codes only. ";
$somethingsWrong = true;
}
^^这里正则表达式正在工作 这让我觉得我没有正确的正则表达式,但我无法弄清楚正确的表达方式......我想禁止任何数字或符号,只接受字母。< / p>
以下是整个switch语句:
switch ($name) {
case 'firstname' :
if (!preg_match('/^[a-zA-Z]+$/', $firstname)) {
$fnameError = "Please enter your first name. ";
$somethingsWrong = true;
} else if (empty($firstname)) {
$fnameError = "Please enter your first name. ";
$somethingsWrong = true;
}
case 'lastname' :
if (!preg_match('/^[a-zA-Z]+$/', $lastname)) {
$lnameError = "Please enter your last name. ";
$somethingsWrong = true;
} else if (empty($lastname)) {
$lnameError = "Please enter your last name. ";
$somethingsWrong = true;
}
case 'street' :
if (empty($street)) {
$streetError = "Please enter your street address. ";
$somethingsWrong = true;
}
case 'city' :
if (!preg_match('/^[a-zA-Z]+$/', $city)) {
$cityError = "Please enter your city. ";
$somethingsWrong = true;
} else if (empty($city)) {
$cityError = "Please enter your city. ";
$somethingsWrong = true;
}
case 'state' :
if ($state === "") {
$stateError = "Please select a state. ";
$somethingsWrong = true;
}
case 'zip' :
if (!preg_match('/^\d{5}$/', $zip)) {
$zipError = "Standard 5-digit zip codes only. ";
$somethingsWrong = true;
} else if (empty($zip)) {
$zipError = "Standard 5-digit zip codes only. ";
$somethingsWrong = true;
}
case 'email' :
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Email invalid.";
$somethingsWrong = true;
}
case 'creditcard' :
if ($creditCard === "") {
$creditCardError = "Please choose a credit card. ";
$somethingsWrong = true;
}
case 'cc' :
if (!preg_match('/\d{16}|\d{18}/', $ccNumber)) {
$ccError = "Please enter a valid credit card number. ";
$somethingsWrong = true;
} else if (empty($ccNumber)) {
$ccError = "Please enter a valid credit card number. ";
$somethingsWrong = true;
}
case 'cvv' :
if (!preg_match('/\d{3}|\d{4}/', $cvv)) {
$cvvError = "Please enter a valid CVV number. ";
$somethingsWrong = true;
} else if (empty($cvv)) {
$cvvError = "Please enter a valid CVV number. ";
$somethingsWrong = true;
}
case 'ticketnumber' :
if (!preg_match('/^\d$/', $ticketNumber)) {
$ticketError = "Please select your number of tickets.";
$somethingsWrong = true;
}
}