I want to validate my textbox which must be required to fill in, but my code does not run after i press the submit button, the warning does not come out if i submit with black textbox? How to improve the code by only php
?
<?php
if (isset($_POST['submit']))
{
$vperson = $_POST['person'];
if (empty($vperson))
{
$sperson = "Person is required";
}
else
{
$sperson = "";
}
}
?>
<html>
<head>
<h1>Members</h1>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<form method="post" action="members.php">
<table border="1">
<tr>
<td >Number of Person</td>
<td align="center"><input type="text" name="person" ><span ><?php echo $sperson;?></span></td>
</tr>
<tr>
<th colspan="2" align="right"><input type="submit" name="submit" value="submit"></th>
</tr>
</table>
</form>
CodePudding user response:
Your form action is action="members.php"
so this is where you should place your validation. Generally speaking, for such validation I would use ajax request.
If for some reason you can't use JavaScript, try return GET variable with error:
Your main file (lets say it is index.php)
<html>
<head>
<h1>Members</h1>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<form method="post" action="members.php">
<table border="1">
<tr>
<td>Number of Person</td>
<td align="center">
<input type="text" name="person">
<span >
<?php echo $_GET['error'] === 'unknown_person' ? 'Person is required' : ''; ?>
</span>
</td>
</tr>
<tr>
<th colspan="2" align="right"><input type="submit" name="submit" value="submit"></th>
</tr>
</table>
</form>
Add this at the top of your members.php (replace index.php with your file name)
<?php
if (empty($_POST['person'])) {
header('Location: index.php?error=unknown_person');
}