Reputation: 11
This is a tricky question to phrase so I'll try my best. I'm a noob and have little knowledge of php so be kind :D
I want to validate forms on a page that is a form handler, so for example my first page with the form (taken from w3schools):
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
So 'welcome.php' is my 'POST' form handler page. But on this page I also want more forms, and on this page I want to validate the forms on it. Say for example some form like:
<form method="post" action='?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>'>
<input type ="text" name="newBalance"><span class="error">*<?php echo $balanceErr;?></span>
</form>
So i would have some php validation like:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["newBalance"])) {
$balanceErr = "Balance is required";
} else {
$balance = test_input($_POST["newBlance"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$balanceErr = "Only letters and white space allowed";
}
}
...and so on.
Problem is as soon as I enter this page it validate form directly from the previous page and error shows for empty fields on page. Is there some way to avoid this or so I need a new approach?
Upvotes: 1
Views: 387
Reputation: 2358
As i understand your issue, you need to check first that which form submitted in validation snippet.
Insert new hidden field in second form and when you validate newBalance
field, check if action
is set or not. action
field will just set when form2 submitted.
Here is code can help you out.
welcome.php
// Form2
<form method="post">
<input type ="text" name="newBalance"><span class="error">*<?php echo $balanceErr;?></span>
<input type ="hidden" name="action" value="true" />
</form>
Validation
if ($_SERVER["REQUEST_METHOD"] == "POST" and isset($_POST['action'])) {
if (empty($_POST["newBalance"])) {
$balanceErr = "Balance is required";
} else {
$balance = test_input($_POST["newBlance"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$balanceErr = "Only letters and white space allowed";
}
}
May above code helps you.
Upvotes: 3