How to check if required fields are filled in or not? - php

Using core PHP only and nothing else, like JavaScript or clientside programming, I need PHP to check if the form's required fields are filled in or not, and display error message if missed. I need to check using procedural style programming as I'm not into OOP yet and don't understand it.
Html Form
<html>
<head>
<title>
Searchengine Result Page
</title>
</head>
<body>
<form method = 'POST' action = "">
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<label for='url'>url</label>
<input type='url' name='url' id='url' required>
<br>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' required>
<br>
<label for='description'>description</label>
<input type='text' name='description' id='description' required>
<br>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' required>
<br>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' required>
<br>
<button type='submit'>Search!</button>
</form>
</body>
</html>
Php Form Validator
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels_count = count($required_labels);
for($i=0; $i!=$required_labels_count; $i++)
{
if(!ISSET(in_array(($_POST['$required_labels[$i]']),$required_labels))) //Incomplete line as I don't know how to complete the code here.
{
echo 'You must fill-in the field' .'Missed field\'s label goes here'; //How to echo the missed field's label here ?
}
}
?>
I know I need to check against associated array values as it would be easier and less code, but I don't know how to do it.
Notice my error echo. It's incomplete as I don't know how to write that peace of code.
How would you check with the shortest possible code using procedural style?
Anything else I need to know?
NOTE: I do not want to be manually typing each $_POST[] to check if the required ones are filled in or not. I need PHP to loop through the $required_labels[] array and check. Or if you know of any shorter way of checking without looping then I want to know.

First we will have an empty $errors array, and then we will apply the validations, and if any of them fails, we will populate the $errors.
Finally using a helper function errorsPrinter we will print the errors under their labels.
For you PHP validation part use the below code. Note that I also added the part to validate the string and int types too.
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$inputs = $_POST;
$errors = [];
foreach($required_labels as $label) {
if(!isset($inputs[$label]) || empty($inputs[$label])) {
$errors[$label] = array_merge(
["You must fill-in the field."],
$errors[$label] ?? []
);
}
}
foreach($strings_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_string($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be string"],
$errors[$label] ?? []
);
}
}
foreach($ints_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_int($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be int"],
$errors[$label] ?? []
);
}
}
function errorsPrinter($errors, $key)
{
$output = '<ul>';
if(!isset($errors[$key])) {
return;
}
foreach($errors[$key] as $error) {
$output = $output. '<li>' . $error . '</li>';
}
print($output . '</ul>');
}
?>
inside the form you can do something like this:
<form method='POST' action="">
<?php errorsPrinter($errors, 'submission_id') ?>
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<?php errorsPrinter($errors, 'website_age') ?>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<?php errorsPrinter($errors, 'url') ?>
<label for='url'>url</label>
<input type='url' name='url' id='url' >
<br>
<?php errorsPrinter($errors, 'anchor') ?>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' >
<br>
<?php errorsPrinter($errors, 'description') ?>
<label for='description'>description</label>
<input type='text' name='description' id='description' >
<br>
<?php errorsPrinter($errors, 'keyphrase') ?>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' >
<br>
<?php errorsPrinter($errors, 'keyword') ?>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' >
<br>
<button type='submit'>Search!</button>
</form>
Note that the errorsPrinter is just a helper and you can remove it and use $errors array as you want. The sample output of errors is like this:
[
"url" => ["You must fill-in the field."],
"anchor" => ["You must fill-in the field."],
"description" => ["You must fill-in the field."],
"keyphrase" => ["You must fill-in the field."],
"keyword" => ["You must fill-in the field."],
"website_age" => ["This input should be int"]
]

$errors = [];
foreach($required_labels as $field) {
if (!isset($_POST[$field]) || $_POST[$field] == '') {
$errors[$field] = "{$field} cannot be empty";
// echo "${field} cannot be empty";
}
}
And then to output those errors:
<?php
if (count($errors)) {
?>
<div id='error_messages'>
<p>Sorry, the following errors occurred:</p>
<ul>
<?php
foreach ($errors as $error) {
echo "<li>$error</li>";
}
?>
</ul>
</div>
<?php
}
And you could directly output the errors next to the input as well:
<input type="text" id="first_name" name="first_name" placeholder="First Name" />
<?php if (isset($errors['first_name'])) echo "<div class='error_message'>{$errors['first_name']}</div>";?>

Related

I don't know what i did wrong on my code, the error message for php form validation stopped working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I don't know what I did wrong on my code, the error message for php form validation stopped working.
It was working perfectly until i added value attribute to the input so that the user input will persist even if the page refresh and didn't deliver due to typeError.
The form does'nt show any error again but my reason for adding the value attribute is working.
I'm learning php, please help me to understand why i'm having the issue.
I don't understand because i'm not getting any error from php.
This is my code
<?php
// empting the value variables when user have'nt typed anything to prevent error. This is the shorthand of typing samething that's going to have the same value
$email = $title = $ingredients = '';
// put out the error on the html instead of echoing it
// so i used array so that i can neatly put out all the errors instead of using different variables for all
$error = array('email' => '', 'title' => '', 'ingredients' => '');
// check if the form was clicked and retrive the values sent
// i will achieve this by using a default method called isset() and i will check if value is contained in the form using the submit btn, this is because when a user clicks on the form submit, the user have entered a value
if(isset($_POST['submit'])){
// check if the field submited is empty
// we achieve this using a default method called empty()
// we check them one field at a time
// check for email
if(empty($_POST['email'])){
$error['email'] = ' Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if(empty($_POST['title'])){
$error['title'] = ' Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if(empty($_POST['ingredients'])){
$error['ingredients'] = ' Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php'?>
<form action="form.php" method="POST">
<div class="input_div">
<label >Email :</label>
<input type="text" name="email" value=" <?php echo $email ?> ">
<div class="error_msg"><?php echo $error['email']; ?></div>
</div>
<div class="input_div" >
<label >Pizza Title :</label>
<input type="text" name="title" value=" <?php echo $title ?> " >
<div class="error_msg"><?php echo $error['title']; ?></div>
</div>
<div class="input_div" >
<label >Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value=" <?php echo $ingredients ?> ">
<div class="error_msg"><?php echo $error['ingredients']; ?></div>
</div>
<div class="input_div" >
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Other then the issues with whitespace in your inputs you should also be aware of XSS when inserting the values back into the form (like using " would break the form) and also don't populate the errors till needed, this will allow you to easily continue and do the success step without needing to loop over the $errors array and it also allows you to hide the <div class="error_msg"></div> element and only show when there is an error.
Also your missing <head> and <body>, presuming they are in the includes, but doing it that way would make it rather difficult to add additional elements or scripts.
<?php
$email = $title = $ingredients = '';
$error = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check for email
if (empty($_POST['email'])) {
$error['email'] = 'Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if (empty($_POST['title'])) {
$error['title'] = 'Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if (empty($_POST['ingredients'])) {
$error['ingredients'] = 'Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
if (empty($error)) {
// do some thing with $email, $title, $ingredients
die(header('Location: ./thank-you.php'));
}
}
function xss_safe($value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?><!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php' ?>
<form action="form.php" method="POST">
<div class="input_div">
<label>Email :</label>
<input type="text" name="email" value="<?= xss_safe($email) ?>"/>
<?= isset($error['email']) ? '<div class="error_msg">'.$error['email'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Pizza Title :</label>
<input type="text" name="title" value="<?= xss_safe($title) ?>"/>
<?= isset($error['title']) ? '<div class="error_msg">'.$error['title'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value="<?= xss_safe($ingredients) ?>"/>
<?= isset($error['ingredients']) ? '<div class="error_msg">'.$error['ingredients'].'</div>' : '' ?>
</div>
<div class="input_div">
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Seeing as your error checking is merely for empty/missed input fields it's easier to just make the inputs required as per HTML5. Here's a simplified version using placeholders for information after the form has been submitted.
Warning: If you are going to be inserting this data into a MySQL table, you need to sanitize the inputs first!
<?php
$email = $title = $ingredients = "";
if (isset($_POST["submit"])) {
$email = $_POST["email"];
$title = $_POST["title"];
$ingredients = $_POST["ingredients"];
}
echo "
<form method='POST'>
<label>Email:</label>
<input type='email' name='email' placeholder='$email' required>
<label>Pizza Title:</label>
<input type='text' name='title' placeholder='$title' required>
<label>Ingredients (comma seperated):</label>
<input type='text' name='ingredients' placeholder='$ingredients' required>
<input type='submit' name='submit' value='Submit'>
</form>
";
?>

Single form multiple submit into same array

I was trying to push with a single form using the $_POST method multiple times the same form (with different values) until the array index is 4 (or a number I decide).
So with this html form i want to press submit, push the values into array, then refresh page, reinsert different values and so on until the condition is true.
<?php
if (!isset($count)) {
$person = array(
array(
'name' => '',
'surname' => '',
'phoneNumber' => ''
)
);
}
var_dump($person);
if (!isset($_POST['submit'])) {
echo "<form action=\"index.php\" method=\"post\">
<label for=\"name\">Name</label>
<input type=\"text\" name=\"name\" required>
<br>
<label for=\"surname\">Surname</label>
<input type=\"text\" name=\"surname\" required>
<br>
<label for=\"phoneNumber\">Phone Number</label>
<input type=\"text\" name=\"phoneNumber\" required>
<br>
<input type=\"submit\" value=\"Submit\" name=\"submit\">
</form>";
$count = 0;
} else {
$name = $_POST['name'];
$surname = $_POST['surname'];
$phoneNumber = $_POST['phoneNumber'];
if (count($person) <= 2) {
array_push($person, $name, $surname, $phoneNumber);
//echo "<meta http-equiv=\"refresh\" content=\"0\">";
//echo "Sto inserendo persone";
//echo count($persone);
echo count($person);
//var_dump($persone);
//print_r($persone);
} else {
var_dump($person);
};
}
?>
I was thinking about using $_SESSION but I don't have an idea about how to use it.
I don't want to use AJAX or jQuery or Javascript only pure PHP.
The example below shows always the form and your actual persons array. If you submit the form, your data will add to the array until it counts more than three entries. I think that is what you are looking for:
<?php
session_start();
if (!isset($_SESSION['persons'])) {
$_SESSION['persons'] = [];
}
if(isset($_POST['submit'])) {
if (count($_SESSION['persons']) <= 2) {
$_SESSION['persons'][] = array(
'name' => $_POST['name'],
'surname' => $_POST['surname'],
'phoneNumber' => $_POST['phoneNumber']
);
}
}
?>
<pre><?php var_dump($_SESSION['persons']); ?></pre>
<form action="index.php" method="post">
<label for="name">Name</label>
<input type="text" name="name" required><br>
<label for="surname">Surname</label>
<input type="text" name="surname" required><br>
<label for="phoneNumber">Phone Number</label>
<input type="text" name="phoneNumber" required><br>
<input type="submit" value="Submit" name="submit">
</form>
With the following line of code you can clear you array if you need to:
$_SESSION['persons'] = [];

PHP - Validate if textbox has a value or not?

I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>

How to start validating php form only after I clicked submit

I am new to php and web development. I am trying to do a simple validation of text field. I want to display a red remark beside the text field after submit button was clicked.
However my problem here is: The php codes validates all input field the moment the page was loaded. How to validate it only after user clicked the submit button?
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type='text' name='name' /><br>
Email <input type='text' name='email' /><br>
Age<input type='text' name='age' /><br>
<input type='submit' name='Done' /><br><br>
</form>
<?php
if(empty($POST['name']))
echo '<font color="red">Please enter your name.</font>';
if(empty($POST['email']))
echo '<font color="red">Please enter your email.</font>';
if(empty($POST['age']))
echo '<font color="red">Please enter your age.</font>';
?>
I have several questions here:
1) If I want to display the error message right beside each text field, shall I write a separate php code beside each input field?
2) How to echo the error message only after user clicked the submit button?
I know this is extremely simply to many people here, but this is my first time doing something related to the web.
Just check if post is send
<?php
if($_POST)
{
if(empty($POST['name']))
echo '<font color="red">Please enter your name.</font>';
if(empty($POST['email']))
echo '<font color="red">Please enter your email.</font>';
if(empty($POST['age']))
echo '<font color="red">Please enter your age.</font>';
}
?>
Please note:
<input type='submit' name='Done' /><br><br>
should be outside the PHP markup.
To display the errors beside each element, just move your if statements to the place where it should be displayed in the HTML.
Most developers use javascript for form validation. A quick Google will give you a lot information about this.
Use $_SERVER['REQUEST_METHOD'] to detect whether the page is being displayed in response to posting the form.
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty($_POST['name'])) {
echo '<span style="color: red;">Please enter your name.</span>';
}
if(empty($_POST['email'])) {
echo '<span style="color: red;">Please enter your email.</span>';
}
if(empty($_POST['age'])) {
echo '<span style="color: red;">Please enter your age.</span>';
}
}
If you want to show them separately next to each input, you can write:
Name <input type='text' name='name' /> <?php
if ($_SERVER['REQUEST_METHOD'] == "POST" && empty($_POST['name'])) {
echo '<span style="color: red;">Please enter your name.</span>';
} ?><br>
Note that the variable containing POST parameters is $_POST, not $POST.
Just add a hidden input to your form.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type='text' name='name' /><br>
Email <input type='text' name='email' /><br>
Age<input type='text' name='age' /><br>
<input type='submit' name='Done' /><br><br>
<input type="hidden" name='form' value='wasSubmited' />
</form>
Then in the PHP script check $_POST:
if ($_POST['form'] == 'wasSubmited') {
// here you can start to validate your form
}
To follow the DRY system you can simplify your code a little and make it easy to adjust in case you add more fields to your form in the future. You only have to add your new fieldname(s) to the $fields array. It is also much easier to adjust the HTML in case you want another class or something.
if(whatever condition you need)
{
$fields = array('name', 'email', 'age');
foreach ( $fields as $field ) {
if(empty($POST[$field]))
echo '<font color="red">Please enter your ' . $field . '.</font>';
}
}
}
try this i used your form working 100% =)
<script>
function ValidateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var age = document.getElementById('age').value;
if (name == "" && email == "" && age == "")
{
document.getElementById("error_name").innerHTML = "Please enter your name<br/>";
document.getElementById("error_email").innerHTML = "Please enter your email<br/>";
document.getElementById("error_age").innerHTML = "Please enter your age";
return false;
}
else if (name == "")
{
document.getElementById("error_name").innerHTML = "Please enter your name<br/>";
return false;
}
else if (email == "")
{
document.getElementById("error_email").innerHTML = "Please enter your email<br/>";
return false;
}
else if (age == "")
{
document.getElementById("error_age").innerHTML = "Please enter your age";
return false;
}
}
</script>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onSubmit="return ValidateForm()">
Name <input type='text' id="name" name='name' /> <span id="error_name" style="color:red;"></span> <br>
Email <input type='text' id="email" name='email' /> <span id="error_email" style="color:red;"></span><br>
Age<input type='text' id="age" name='age' /> <span id="error_age" style="color:red;"></span><br>
<input type='submit' name='Done' /><br><br>
</form>
Here is a pure php printing the error right beside the form fields
<?php
$fieldErrors = array();
if(isset($_POST['Done']))
{
$fields = array('name', 'email', 'age');
foreach ($fields as $field)
{
if($_POST[$field] == "")
{
$fieldErrors[] = $field;
}
}
}
if(count($fieldErrors) > 0)
print_r($fieldErrors);
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type='text' id="name" name='name' /> <span id="error_name" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("name", $fieldErrors)) ? 'Please Enter your name' :''; ?></span> <br>
Email <input type='text' id="email" name='email' /> <span id="error_email" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("email", $fieldErrors)) ? 'Please Enter your email' :''; ?></span><br>
Age<input type='text' id="age" name='age' /> <span id="error_age" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("age", $fieldErrors)) ? 'Please Enter your age' :''; ?></span><br>
<input type='submit' name='Done' /><br><br>
</form>

How to show results in textboxes in php

I have this piece of code and I want to show result in the third input box not in the input box and hole page and i want to know if i can a $_GET['$vairbles'] whiten functions
NOTE : I’m beginner in php programming
Here is my code :
<?php
$email = "mail#somedomain.com";
if (isset($_GET['txt1']) and isset($_GET['txt2'])) if (!empty($_GET['txt1']) and!empty($_GET['txt2'])) {
$tex1 = $_GET['txt1'];
$tex2 = $_GET['txt2'];
echo "They are all filled.<br>";
} else {
echo "Please fill in first and second Fields";
}
shwor();
Function shwor() {
global $email;
global $tex1;
global $tex2;
$len1 = strlen($tex1);
$len2 = strlen($tex2);
if ($len1 and $len2 > 0) if ($tex1 == $tex2) echo "matched ";
else echo "Does not match";
}
?>
<form action:"email.php" method="GET">
<input 1 type="text" name="txt1"><br><br>
<input 2 type="text" name="txt2"><br><br>
<input 3 type="text" name="Result" value = "<?php shwor();?>"><br><br>
<input type="submit" value="Check matches"><br>
</form>
everything works, just misspelled in this line:
<form action:"email.php" method="GET">
should be:
<form action="email.php" method="GET">
..and remember to name your file email.php that the data will be sent to the file itself ;-)

Categories