如何回复表单输入而无需在验证后重新显示表单?我只能在表单后显示输入。这是我的代码
<?php
$postalCode = $_POST['postalCode'];
$postalCodeErr = "";
$postalCodeValidation = '/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/';
$postalCodeIsValid = false;
?>
<html>
<body>
INT322 Lab 3-1
<br />
<br />
<form name="lab3form" action="index.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php
if(($postalCode != "") && preg_match($postalCodeValidation, $postalCode)) {
$postalCodeIsValid = true;
}
else {
$postalCodeErr = "Invalid Postal Code";
}
if(isset($postalCode)) echo " $postalCodeErr";
?>
<br />
<br />
<input type="submit" name="submit" />
</form>
</body>
</html>
<?php
if($_POST['submit'] && $postalCodeIsValid) {
echo "Postal Code: $postalCode";
}
?>
答案 0 :(得分:1)
如何将表单打包在else
的{{1}}
if($_POST['submit'] && $postalCodeIsValid) { ... } else { ... }
完整代码的更新答案:
<?php
if($_POST['submit'] && $postalCodeIsValid) {
echo "Postal Code: $postalCode";
}
else {
<form name="lab3form" action="index.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php
if(($postalCode != "") && preg_match($postalCodeValidation, $postalCode)) {
$postalCodeIsValid = true;
}
else {
$postalCodeErr = "Invalid Postal Code";
}
if(isset($postalCode)) echo " $postalCodeErr";
?>
<br />
<br />
<input type="submit" name="submit" />
</form>
}
?>
请注意,您的正则表达式仅适用于<html>
<body>
INT322 Lab 3-1
<br />
<br />
<?php
if(!empty($_POST['submit'])):
$postalCode = $_POST['postalCode'];
if(isValidPostalCode($postalCode)):
echo "Postal Code: $postalCode";
else:
form($postalCode, true);
endif;
else:
form();
endif;
?>
</body>
</html>
<?php
function form($postalCode = null, $hasError = false) { ?>
<form name="lab3form" action="postal.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php if ($hasError): ?>
<div class="error">Invalid Postal Code</div>
<?php endif; ?>
<br />
<br />
<input type="submit" name="submit" />
</form>
<?php }
function isValidPostalCode($postalCode) {
$postalCodeValidation = '/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/';
return !empty($postalCode) && preg_match($postalCodeValidation, $postalCode);
}
?>
等邮政编码 - 我不确定这是否是您想要的行为。