我用php编写了一些代码来验证我的表单中的邮政编码字段。该代码旨在检查字段是否为空(强制)并匹配5个可用的邮政编码之一,如果不匹配,则显示警报。我遇到的问题是,当我离开字段空,并点击提交按钮,适当的警报显示,但如果我输入一个错误的值,并点击提交表单只是加载到一个空白的屏幕,有人能发现我的代码中的错误吗?:
<?php
if (isset($_POST['submit'])) {
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "";
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
return true;
}
$msgp = '<span class="error"><b>Please enter correct postcode</b></span>';
return false;
} else if(empty($post)) {
$msgp = '<span class="error"><b>Please enter postcode</b></span>';
}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi">
<b>Post Code</b>
<br>
<input type="text" id="post" name="post" /><?php echo $msgp; ?>
</form>
return
?回哪里?
当你在主代码中返回时,它(几乎)与die()'ing相同。
所以当你返回时,剩下的PHP将不再被执行。
我会考虑设置一些变量,如$success = true/false;
,而不是返回
在$msgp = '<span class="error"><b>Please enter correct postcode</b></span>';
之后返回false,因此您不能继续下面的表单…从代码中删除返回,以便能够处理和显示错误。
您正在使用return
。你是在function() {}
里吗?如果是这样,则所有变量都在函数范围内。您可以执行global $msgp;
,使变量可以在函数外部访问。
如果不是……那么你就不应该使用return
修改php代码为
<?php
if (isset($_POST['post'])) {
$post = intval($_POST["post"],0);
$words = array(2747,2750,2756,2760,2777);
$msgp = '<span class="error"><b>'.in_array($post,$words) ? "Please enter postcode" : "Please enter correct postcode" .'</b></span>';
}
有很多事情可以简化。例如代码为int数组并使用in_array()
函数。Return语句应该用于在全局范围内使用它从方法/函数返回一些东西,然后当前脚本文件的执行结束。这里不需要它。如果有更多的$words值,您应该考虑使用简单的REGEX /[0-9]{4}/
和preg_match()
您想显示$msgp
对吗?使用echo $msgp;
。但是您可以在代码中返回到任何地方。(把它放在一个函数中)。
试试这个
<?php
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "<span class='error'><b>Please enter correct postcode</b></span>";
function check($post){
global $words;
$return=true;
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
//$return=true;
}
} else if(empty($post)) {
$return=false;
}
return $result;
}
$return=check($post);
if($return === true){
// echo you are right!
}
else {
echo $msgp;
}