I want to display an error on the same page if any field is empty.
I've got this, which works but the empty error is displayed as soon as the page is loaded instead of appearing once empty fields are submitted.
<?php
// Required field names
$required = array('triangleSide1', 'triangleSide2', 'triangleSide3');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field)
{
if (empty($_POST[$field]))
{
$error = true;
}
}
if ($error)
{
echo "ALL FIELDS ARE REQUIRED";
}
else
{
echo header('Location: formSuccess.php');
}
?>
Any ideas? -- UPDATE // IVE TRIED ALL ANSWERS, nothing has worked so far
Wrap everything you check on post in this:
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
// Your code containing checks here
}
This way, it will only trigger when a POST request is used.
If you have an input you know will always be submitted with the form, such as a hidden one:
<input type='hidden' name='formsubmit' value='1'>
Then you can test for this before validating the other inputs
if($_POST["formsubmit"]) {
// Required field names
$required = array('triangleSide1', 'triangleSide2', 'triangleSide3');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "ALL FIELDS ARE REQUIRED";
} else {
header('Location: formSuccess.php');
}
}
Also you don't echo the return of header()
OR another way ( I have something similar in one of my pages)
function check_presence($value){
return isset($value) && $value!=="";
}
function validate($required){
global $error
foreach($required as $field){
$value = trim($_POST[$field]);
if (!check_presence($value)){
$error = true;
}
}
return $error;
}
then on the page containing the form and its validation code
$required = array('triangleSide1', 'triangleSide2', 'triangleSide3');
if(isset($_POST["submit"]){
$error = validate($required);
if ($error){
echo "ALL FIELDS ARE REQUIRED";
}
}
Try isset instest of empty!!!
if (empty($_POST[$field]))
Become
if (isset($_POST[$field]))
Related
HTML markup
<input name="one[name]">
<input name="one[email]">
<input name="two[message]">
...
alot input
..
I pass that two array data from jquery to php, i need check if the field is empty by php and exit when find one of them is empty.
But i dont want do it one by one, can it done by php function like foreach or other?
This is what i tried but fail.
$data_one = $_POST['one'];
$data_two = $_POST['two'];
if (empty( $_POST['one'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Above code keep return field are filled message, whether i fill the input field or not.
Thanks so much.
$allFilled = true;
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
$allFilled = false;
exit('some fields are empty');
}
}
if($allFilled){
exit('all fields are filled');
}
Making use of array_filter and count functions
<?php
$data_one = $_POST['one'];
$data_one_filter = array_filter($_POST['one']); //Remove indexes of null or 0 - certainly name and email can't be 0
$data_one_count = count($_POST['one']); //count actual number of POST variables
$data_two = $_POST['two'];
if (count($data_one_filter) === $data_one_count) {
exit('fields are filled');
} else {
echo('some fields are empty');
// continue other function
}
You are sending data as array. So you seed to check this data as array like this:
$data_one = $_POST['one']['name'];
$data_two = $_POST['two']['message'];
if (empty( $_POST['one']['name'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Try this
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
exit('some field are empty');
}
}
echo "All fields are filled";
I have a form with 25+ fields. I want to display a message if ANY of the fields in the array are NOT empty.
$customfields = array('q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10', 'q11', 'q12', 'q13', 'q14', 'q15', 'q16', 'q17', 'q18', 'q19', 'q20', 'q21', 'q22', 'q23', 'q24');
I've taken a look at similar SO questions for verifying that all fields are not empty, i.e.:
$error = false;
foreach($customfields as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "Here's an awesome message!";
} else {
echo "None for you, Glen Coco.";
}
How do I do the opposite - display a message if ANY one or more than one fields in the array are not empty?
Thanks in advance!
I think you want to take a look into the NOT operator.
You can just write this:
if (!empty($_POST[$field])) {
//^ See here the NOT operator
$error = true;
}
For more information see the manual: http://php.net/manual/en/language.operators.logical.php
Do the opposite comparison in the if:
$error = false;
foreach($customfields as $field) {
if (!empty($_POST[$field])) {
$error = true;
break; // get out of foreach loop
}
}
I am trying this code as part of form processing:
<?php
if(isset($_POST['senderEmail']))
{
try
{
require '_php/_security/validation.php'; //SEE BELOW
$rules = array(
'senderEmail' => 'validEmail',
'emailTextbox' => 'validTextbox',
);
$validation = new Validation();
if ($validation->validate($_POST, $rules) == TRUE) {
require("_php/database/dbProcessing.php"); //Form Proccessing for database inclusion
}
else {
foreach($validation->emailErrors as $error){
$emailErrors[] = $error;
$_SESSION['$emailErrors'] = $emailErrors;
header('Location:indexmobile.php#emailErrors');
die('ABORT!');
}
}
}
catch (PDOException $e)
{
$error = 'Error adding elements to database: ' . $e->getMessage();
echo "Error: " . $error;
exit();
}
exit();
}
?>
The validation.php where I do my validation has this:
<?php
class Validation {
public $errors = array();
public function validate($data, $rules) {
$valid = TRUE;
foreach ($rules as $fieldname => $rule) {
$callbacks = explode('|', $rule);
foreach ($callbacks as $callback) {
$value = isset($data[$fieldname]) ? $data[$fieldname] : NULL;
if ($this->$callback($value, $fieldname) == FALSE) $valid = FALSE;
}
}
return $valid;
}
public function validEmail($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$valid = filter_var($value, FILTER_VALIDATE_EMAIL);
if ($valid == FALSE) $this->emailErrors[] = "The $fieldname needs to be a valid email";
return $valid;
}
}
public function validTextbox($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$whitelist = '/^[a-zA-Z0-9 ,\.\+\\n;:!_\-#]+$/';
$textarea = strip_tags($value);
$textarea = mysql_real_escape_string($textarea);
$valid = preg_match($whitelist, $textarea);
if ($valid == FALSE) $this->errors[] = "The $fieldname contains invalid characters";
return $valid;
}
}
}
Upon using this, Im have issues with the redirect (I think). It seems further that Im having errors in validation. My questions are thus:
Am I doing the header redirect correctly? I've read that " header() must be called before any actual output is sent,.." So is this the reason why this redirect is incorrect? how to make a redirect if i need to show/send something to the redirected page?
function validTextbox always ends up an error that the field is empty. Why so?
Is my entire process of form validation a good way of validating form fields (which i learned from watching an online tutorial)? What is a better way?
Is there something wrong with error reporting in this case?
Thank you for those who replies. I am new to PHP and trying my best to learn the language.
1 - There are several ways to pass on a message to the page you are redirecting to. One is through $_GET like this
$message="Some message for the next page.";
$message=urlencode($message);
header("Location:page.php?message=".$message);
then on page.php
if(!empty($_GET['message']))
{
$_GET['message'];
}
similarly you can also use the session (less secure)
$_SESSION['message']='some other message';
then on page.php
if (!empty($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
2 - I would have to see what you are passing to your validate function. You should do a var_dump of $_POST and add that to your question.
3 - It depends on your criteria. If you are just checking for emptiness its overkill. I don't know what text you need / consider valid, but a regex is a reasonable way of enforcing validation.
4 - See #2.
I have 2 textboxes one is for maximum marks and the other for the obtained marks..
The value to be entered in the second box must be restricted in such a way that it is less than or equal to the maximum marks.. Only numbers must be entered into those boxes..
Maximum Marks<input type=text name=maxmarks maxlength='2' >
Obtained marks<input type='text' maxlength='2' name='obtmarks'>
Please help me with this.. Thank you in advance..
Well if you want to do it client side, you will have to use Javascript. If you want to do it server-side, why don't you send them back the page with an error message if the second number exceeds the first. You might also might want to look into HTML5 input options if that is an available option for you. Those will automatically do the number validation.
You could try something like this...
$response_array = array();
if($obtained > $max){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained to big</div>';
}
if(!is_numeric($obtained){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained not a number</div>';
}
echo json_encode($response_array);
This is pseudo code, obviously you will need to tweak it for your purpose.
First you have to make checks in your php script that you submit the form, you can use javascript after to make it more user friendly but if someone change the source code or just turn javascript off he will be able to submit anyting.
In your process_form.php:
session_start();
$errors = array();
if (!isset($_POST['maxmarks']) || empty($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field is required.';
}
else {
if (!is_int($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field must be an integer.';
}
else {
$maxmarks= (int) trim($_POST['maxmarks']);
}
}
if (!isset($_POST['obtmarks']) || empty($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field is required.';
}
else {
if (!is_int($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field must be an integer.';
}
else {
$obtmarks= (int) trim($_POST['obtmarks']);
}
}
if (!empty($errors)) {
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else if ($obtmarks > $maxmarks){
$errors[] = 'The Obtained Marks must be less or equal to Maximum Marks.';
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else {
//process data
}
In your_form.php now:
session_start();
if (isset($_SESSION['form_errors']) && !empty($_SESSION['form_errors'])) {
$errors = $_SESSION['form_errors'];
unset($_SESSION['form_errors']);
}
echo '<ul>';
if (isset($errors)) {
foreach($errors as $error) {
echo '<li>' . $error . '</li>';
}
}
echo '</ul>';
//your form here
I've a form,in the form only few fields are mandatory.When a fields is not mandatory,it should not check for empty data validation.If the non mandatory field contain data then it shoudl check the data,validation should happen only when data present.
My below code check for all fields.For eg:Say phone is not mandatory in below code,how to change the code.
$validate = array(
array($x, '/^[a-z\d ]{4,20}$/i', "Please enter valid name."),
array($y, '/^[a-z\d ]{4,20}$/i', "Please enter a real category."),
array($phone, '/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/' , "Please enter a valid phone number")
);
$error = '';
foreach ($validate as $validation)
{
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
if($error != '')
{
echo $error;
exit;
}
Comment on this post,if it is not clear.
Thanks in advance!
If you want to check if at least required fields have been submitted, you can check whether they have been set and have a truthy value using the isset and empty functions.
For example:
if ( isset($_POST['username'], $_POST['password']) &&
! empty($_POST['username']) && ! empty($_POST['password']) ) {
// validation here
}
That would check if the username and password fields were submitted and have a value, whereas for example an email field wouldn't necessarily have been filled in for the above condition to return true.
If you know the mandatory fields before hand I'll suggest you group them in an array and test for based on the current key. If a key is in not mandatory but holds value you can test otherwise do your regular check.
$error = '';
$mandatoryFields = array('key1', 'key2' 'key3');
foreach ($validate as $validation)
{
if (!in_array($validation[0], $mandatoryFields) && strlen(trim($validation[0])) > 0)
{
// There is data in a non mandatory field.
// Perform your test.
}
else {
// Do your regular test.
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
}
You can give this a try.