I'm trying to create a function. which will check if the field is empty or not. If the input is empty it'll push an error for that input in the error array.
$errors = ["name" => "Name is required"];
like so
How can I do this?
function checkRequiredFields($fields = [], $errors = [])
{
foreach ($fields as $field) {
if (is_blank($field)) {
$errors[$field] = "$field is required";
}
}
}
btw here's how my is_blank function looks:
function is_blank($value)
{
return !isset($value) || trim($value) === '';
}
You can check that the field has been submitted and doesn't hold the empty string:
<?php
function check_required_fields($fields, &$errors) {
foreach($fields as $fieldname) {
if(isset($_POST[$fieldname]) && $_POST[$fieldname] === '') {
$errors[$fieldname][] = "'$fieldname' is required.";
}
}
}
check_required_fields(['email'], $errors);
?>
<form method='POST'>
<input type='text' name='name'>
<input type='email' name='email'>
<input type='submit'>
</form>
You can get the values of the input fields with
$field = $_GET["field"]; // or $_POST["field"]; depending of your form.
But you need to sanitize properly your input values for security reasons.
https://www.php.net/manual/fr/function.filter-input.php
The empty() function is also what you're looking for.
if (empty($field)) {
$errors[$field] = "$field is required";
}
Checkout the documentation : https://www.php.net/manual/fr/function.empty.php
Take a look at the isset() function also.
Related
I have a basic form with a dozen fields (I would take 3 for example):
<input type="text" name="user_first_name" class="form-control" pattern="[A-Za-z-]+" required />
<input type="text" name="user_last_name" class="form-control" pattern="[A-Za-z-]+" required />
<input type="tel" name="user_phone" class="form-control" />
...
Only the phone number can be empty, the last name and first name are obligatory and can contain only letters and dashes (the technical constraints were imposed on me by our old ERP)
I created a function to clean up all my fields that looks like this:
public function sanitizeInfo($user_first_name, $user_last_name, $user_phone) {
$user_first_name = preg_replace('/[^A-Za-z-]/', '', $user_first_name);
$user_last_name = preg_replace('/[^A-Za-z-]/', '', $user_last_name);
$user_phone = (isset($user_phone) and !empty($user_phone)) ? preg_replace('/[^A-Za-z0-9+-.)(]/', '', $user_phone) : NULL;
$array = array(
"first_name" => $user_first_name,
"last_name" => $user_last_name,
"phone" => $user_phone
);
return $array;
}
In my PHP script I make this first check:
$fields = array('user_first_name', 'user_last_name');
$error = FALSE;
foreach ($fields as $fieldname) {
if(!isset($_POST[$fieldname]) or empty($_POST[$fieldname])) {
$error = TRUE;
$message = 'err';
}
}
if (error === TRUE) {
echo "Error !"
} else {
$info = sanitizeInfo($_POST['user_first_name'], $_POST['user_last_name'], $_POST['user_phone']);
...
** QUERY **
}
I want to check, before sending this in database, that the fields are not empty (only the telephone number can be NULL)
But the problem right now is that I do not know if my non-required fields exist and especially my sanatizeInfo function is problematic because it allows to put empty fields in database
Example:
The user enters "!! -" as firstname and the sanitizeInfo function returns "" because the preg_replace to delete these characters
How to avoid this?
All you need to do is calling the function sanitizeInfo before checking empty fields and replacing your foreach loop with a simple array_search function.
This can be implemented as follows:
$fields = array('user_first_name', 'user_last_name');
$error = FALSE;
$values = sanitizeInfo($fields[0], $fields[1], #$fields[2]);
$arSear = array_search('', $values);
if ($arSear !== FALSE && $arSear != 'phone'){
$error = TRUE;
$message = 'The field `'.$arSear.'` is empty.';
}
if ($error) {
echo 'Error: '. $message;
} else {
// QUERY ....
}
As a matter of consistency, I recommend always using && and || in php versus AND and OR. This will prevent any trip ups regarding precedence. 'AND' vs '&&' as operator
I apologize for this being a bit lengthy but I wanted to show the code and not leave anything out.
The Goal: The user submits a registration form that submits the form to a database which adds the info plus a unique string to the database. Once the user submits an email is sent to the user that contains a link to a php page that has that unique string as a URL identifier at the end like so:
xyz.com/activate.php?uid=292ca78b727593baad9a
When the user clicks that link they are taken that page where they will fill out another form and when they click submit it will activate their account.
The Problem: When the user goes to the link provided they receive an error from my validation page like so:
Undefined index: variable in process.php
BUT when the user deletes the URL identifier so the URL shows as:
xyz.com/activate.php
The user does not receive an error and the validation page (process.php) works properly. I have attempted to use the identifier with a $_GET['uid'] and checking if it exists before running the code but the result was the same. I cannot find an answer when attempting to google this issue so I apologize if this has been asked before.
The Question: Why does this work without the URL identifier but not with it? I do realize the URL identifier basically does a $_REQUEST when the page first loads which is what runs the process.php. Is there a way to prevent that?
So that you guys know the code I am working with I have posted it below.
activate.php:
<?php
// validate the form.
require_once('process.php');
$validation_rules = array(
'company_name' => array(
'required' => true,
'min-length' => 2
)
);
$db_error = '';
$validate = new validator();
$validate->validate($validation_rules);
if ($validate->validate_result()) {
// the validation passed!
}
?>
<div class="bg v-100 cm-hero-activate">
<div class="v-100">
<div class="v-set v-mid">
<form class="v-mid v-bg-white <?php if(!$validate->validate_result() && $_POST || !empty($error)) { echo "shake"; } ?>" name="activation" action="" method="post">
<fieldset>
<div class="form-content">
<div id="content">
<div class="form-inner in" data-id="1" data-name="activate">
<h1>ACTIVATE YOUR ACCOUNT</h1>
<div class="form-section">
<h2>Personal Info</h2>
<?php if (!empty($db_error)) {
echo $db_error;
} ?>
<div class="field-group">
<input type="text" id="company_name" class="field required" name="company_name" value="<?php $validate->form_value('company_name'); ?>">
<label for="company_name" class="placeholder">Company Name</label>
<?php $validate->error(array('field' => 'company_name', 'display_error' => 'single')); ?>
</div>
</div>
<div class="field-bottom">
<button name="submit" data-name="activate" class="bttn btn-dark btn-hover-gloss">ACTIVATE MY ACCOUNT</button>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
process.php:
<?php
class validator {
private $validation_rules;
private $errors = array();
private $validate_result = array();
public function validate($rules) {
$this->validation_rules = $rules;
if($this->validation_rules && $_REQUEST) {
foreach($this->validation_rules as $field => $rules) {
$result = $this->process_validation($field, $rules);
if($result == false) {
$this->validate_result[] = 0;
} elseif($result == true) {
$this->validate_result[] = 1;
}
}
}
}
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && $_REQUEST[$field_name]) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
public function validate_result() {
if($this->validation_rules) {
if($_REQUEST) {
$final_result = true;
$length = count($this->validate_result);
for($i=0;$i < $length; $i++) {
if($this->validate_result[$i] == 0) {
$final_result = false;
}
}
return $final_result;
}
}
}
private function process_validation($field, $rules) {
$result = true;
$error = array();
foreach($rules as $rule => $value) {
if($rule == 'required' && $value == true) {
if(!$this->required($field, $value)) {
$error[] = "$field - required";
$result = false;
}
} elseif($rule == 'min-length') {
if(!$this->minlength($field, $value)) {
$error[] = "$field - minimun length is $value";
$result = false;
}
}
}
$this->errors[] = array($field => $error);
return $result;
}
public function error($data = '') {
if($this->validation_rules) {
if($_REQUEST) {
foreach($this->errors as $err) {
if(isset($data['field'])) {
foreach($err as $field => $field_error) {
if($data['field'] == $field) {
foreach($field_error as $error_data) {
if(isset($data['display_error']) == 'single') {
echo '<p class="error">' . $error_data . '</p>';
goto next;
} else {
echo '<p class="error">' . $error_data . '</p>';
}
}
next:
}
}
} else {
foreach($err as $field => $field_error) {
foreach($field_error as $error_data) {
if(isset($data['display_error']) == 'single') {
echo '<p class="error">' . $error_data . '</p>';
goto next1;
} else {
echo '<p class="error">' . $error_data . '</p>';
}
}
next1:
}
}
}
}
}
}
private function required($field, $value) {
if(empty($_REQUEST[$field])) {
return false;
} else {
return true;
}
}
private function minlength($field, $value) {
if(strlen($_REQUEST[$field]) < $value) {
return false;
} else {
return true;
}
}
?>
EDIT: it seems that the error is happening on the if statement in the min-length function: if(strlen($_REQUEST[$field]) < $value)
EDIT 2: This may also be of some use. The textbox is being filled with this: <br /><font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'><tr><th align='left' bgcolor='#f57900' colspan=
and underneath that I receive this error: Notice: Undefined index: company_name in C:\...\process.php on line 25 Call Stack #TimeMemoryFunctionLocation 10.0005369632{main}( )...\activate.php:0 20.0029403928validator->form_value( )...\activate.php:80 ">
Your $field_name doesn't exist in the $_REQUEST array which is why you are getting your undefined index error.
You are not checking if the value is set - just accessing it via $_REQUEST[$field_name] in your if statement.
Change
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && $_REQUEST[$field_name]) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
To
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && isset($_REQUEST[$field_name])) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
Unrelated Tips.
Aim for cleaner - and more concise readable code.
$input = [
'name' => 'Matthew',
];
$rules = [
'name' => 'required|string',
];
$v = (new Validator())->validate($input, $rules);
if ($v->fails()) {
// Do something with $v->errors();
return;
}
// Do something with validated input
Try and avoid using else or elseif wherever possible. This can be achieved by looking for the negative first, and exiting early. Try not to have too many levels of nesting. It makes your code extremely difficult to read and increases cyclomatic complexity.
Also - take a look at an MVC framework which should help you to structure your code. A good start would be something like Laravel https://laravel.com/ there are good tutorials on https://laracasts.com/
You are getting this error because you have logic like
if($this->validation_rules && $_REQUEST) {
In PHP, an empty array is falsy and a non-empty one, truthy.
$_REQUEST is a combination of $_GET, $_POST and $_COOKIE.
When you add the uid query parameter, $_REQUEST will not be empty and therefore not falsy and your validator will attempt to run but without the expected POST data (such as company_name).
If you're only wanting to validate POST data, you should only be inspecting $_POST.
See Gravy's answer for safer ways to check for the existence of array keys.
I am trying to get an post array validated by php, Scenario 2 works , Scenario 1 doesn't - when calling the function inside a loop , Please Help
Scenario 1
// Trying to call the function in the loop
<form action="new_signup_form_upload.php" method="POST">
Email 1 <input type = "text" name = "email[newsignup_email1]">
Email 2 <input type = "text" name = "email[newsignup_email2]">
<input type="submit" id= "submit" name= "submit">
function validate_email(){
if ($value == "") {
echo $nameErr = '<div id = "error_message_div">Name is required</div>';
return false;
}
else{
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
echo $emailErr = '<div id = "error_message_div">Invalid email format</div>';
return false;
}
}
}
foreach($_POST[email] as $key => $value){
validate_email();
}
Scenario 2
// The difference here is am writing the function when inside the loop
<form action="new_signup_form_upload.php" method="POST">
Email 1 <input type = "text" name = "email[newsignup_email1]">
Email 2 <input type = "text" name = "email[newsignup_email2]">
<input type="submit" id= "submit" name= "submit">
foreach($_POST[email] as $key => $value){
if ($value == "") {
echo $nameErr = '<div id = "error_message_div">Name is required</div>';
return false;
}
else{
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
echo $emailErr = '<div id = "error_message_div">Invalid email format</div>';
return false;
}
}
}
the function validate_email does not have any access to outside variables (except the really really global ones). Besides a lot of other objections to the code.. you should pass the $value in your foreach loop
function validate_email($value){
if ($value == "") {
echo $nameErr = '<div id = "error_message_div">Name is required</div>';
return false;
}
else{
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
echo $emailErr = '<div id = "error_message_div">Invalid email format</div>';
return false;
}
}
}
foreach($_POST[email] as $key => $value){
validate_email($value);
}
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]))
I have a user defined function, it takes one argument as an array for the form required fields. It checks if these fields are empty or not. If they are empty it will return a message and stop processing the form.
<?php
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
}
}
return "You have errors";
}
$required_array = array('name', 'age');
if (isset($_POST['submit'])) {
echo check_required_fields($required_array);
}
?>
<html>
<body>
<form action="#" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
The function is returning this error even when the form required fields are filled? how to fix this?
How can i use just use the function with out writing the word echo before its name?
I want to use this function so i don't have to manually write the if and else statement for every field in the form.
I think you want to do like this?
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
return "You have errors"; //This indicates that there are errors
}
}
}
or why not just:
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname])) {
return "You have errors"; //This indicates that there are errors
}
}
}
UPDATE:
Change:
$required_array = array('name', 'age'); //This just sets strings name and age into the array
to:
$required_array = array($_POST['name'], $_POST['age']); //This takes the values from the form