Reputation:
I have created an HTML form that stores data in a database and later on I take them, and today I wanted to make it more advanced.
I have a form that looks like this (not for login, just for example)
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name"/>
Surname: <input type="text" name="surname" />
Phone: <input type="text" name="phone" />
<input type="submit" />
In process.php, it stores data in the database so later I can use them.
I want to make it so if one or more of them are empty, when you press submit button it shows error like "Must fill all fields", but if you have done everything, it just submits and stores data in database.
I thought I can make with this kind of code:
<?php
$required = array('name', 'surname', 'phone');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
Write an error message and don't react to submit
}
else {
If everything is done, allow to submit
}
?>
How can I make it work, so that you can't press Submit while you haven't finished all fields?
Upvotes: 0
Views: 3596
Reputation: 1792
Easiest and quickest way, You can use HTML5 required
.
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name" required />
<BR>
Surname: <input type="text" name="surname" required />
<BR>
Phone: <input type="text" name="phone" required />
<BR>
Gender: Male <input type="radio" name="gender" value="1" required />
Female <input type="radio" name="gender" value="2" required />
<BR>
<input type="submit" />
</form>
Upvotes: 0
Reputation: 11
You're wanting something client side to validate the fields before you're able to submit to the next page. Look up validation in jQuery and maybe include the "required" attribute that's been added into HTML5.
Upvotes: 1
Reputation: 235
Try the below code
<?php
if(isset($_POST['submit'])){
$required = array('name', 'surname', 'phone');
$error = false;
$message='';
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
$message = 'All fields required';
}else{
//Submit process here
}
}
?>
<?php echo $message; ?>
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name"/>
Surname: <input type="text" name="surname" />
Phone: <input type="text" name="phone" />
<input type="submit" name="submit" value="Submit" />
Upvotes: 0
Reputation: 2587
Add name attribute to button set required to all required fields
<input name="submit" type="submit" />
in php
<?php
if(isset($_POST['submit'])){
$required = array('name', 'surname', 'phone');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
write and error message and don't react to submit
} else {
if everything is done, allow to submit
}
}
?>
Upvotes: 0