Below is my PHP code, currently, it shows all errors and etc, but if one of them are correct it will submit the form, How could I change my code so that if 1 is not correct is does not submit
<?php
$cusMsg = "";
$fNameMsg = "";
if (isset($_POST["submit"])) {
$id = $_POST["custid"];
if(empty($id)) {
$cusMsg = '<span class="error"> Field was left empty</span>';
} else if(!is_numeric($id)) {
$cusMsg = '<span class="error"> Customer ID must be numeric</span>';
} else if(strlen($id) != 6) {
$cusMsg = '<span class="error"> Customer ID must be 6 digits long</span>';
} else {
return true;
}
}
if (isset($_POST["submit"])) {
$fName = $_POST["customerfname"];
$pattern = "/^[a-zA-Z-]+$/";
if(empty($fName)) {
$fNameMsg = '<span class="error"> Field was left empty</span>';
} else if(!preg_match($pattern, $fName)) {
$fNameMsg = '<span class="error"> First name must only containt letters and hyphens</span>';
} else if(strlen($fName) > 20) {
$fNameMsg = '<span class="error"> First name must not be longer than 20 characters</span>';
} else {
return true;
}
}
}
?>
Instead of else in the last use else if and pass this
else if(!empty($fName) && preg_match($pattern, $fName) && strlen($fName) < 20){
return true;
}
It just checks all your condition using AND operator and returns true only if all conditions are met
You could set a flag variable $submit to false by default.
if (isset($_POST["submit"])) {
$submit = false; // Add this
$id = $_POST["custid"];
if (empty($id)) {
$cusMsg = '<span class="error"> Field was left empty</span>';
} else if (!is_numeric($id)) {
$cusMsg = '<span class="error"> Customer ID must be numeric</span>';
} else if(strlen($id) != 6) {
$cusMsg = '<span class="error"> Customer ID must be 6 digits long</span>';
} else {
$submit = true;
}
// Now check the value of $submit and write your code accordingly.
if ($submit) {
// Write your submit action
} else {
// Other action
}
}
Related
how I can define a variable inside a PHP function and make it reachable from another function? I want to set $error variable to "1".
This how would the code look like:
function checkthename ($name){
if ($name == "TESTTEST"){
echo $error = 0;
}
else {
echo $error = 1;
}
}
function phone ($phone){
if ($name == "TESTTEST"){
echo $error = 0;
}
else {
echo $error = 1;
}
}
etc.
And in end of the code there would be an another function which is checking if there is any $error variable set to 1
function checktheerror($error){
if ($error == 0){
echo "no error in this code";
}
elseif ($error == 1){
echo "there is one or multiple errors";
}
}
Thank you so much for your help!
Assume that I am creating a registration form. I have code like the below and it is hard to manage because of all the nested if statements.
I want to know the cleanest and easiest to follow way to write code that functions similarly to what I have below.
EDIT: People have told me that I can move the empty($_POST['email']) to the validation functions. I can't do that because I need to know 1) whether user has posted data or not, and 2) whether the data user posted is valid.
For example, when the user first goes to the registration page, they have not posted any data so $_POST['email'] will generate PHP warnings because they don't exist. That's why I check whether data has been posted before I validate.
Does this make sense?
function validate_email($str) {
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
function validate_password($str) {
$str = trim($str);
if(strlen($str) < 5 || strlen($str) > 70) {
return false;
} else {
return $str;
}
}
$email = false;
$password = false;
$errorMessage = false;
if(!empty($_POST['email'])) {
$email = validate_email($_POST['email']);
if($email) {
if(!empty($_POST['password'])) {
$password = validate_password($_POST['password']);
if($password) {
createNewUser($email,$password);
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "Email address is invalid";
}
} else {
$errorMessage = "Email address is invalid";
}
if($errorMessage) echo $errorMessage;
Whenever you have nested if()s you can flip the logic "inside out":
if (A)
if (B)
if (C)
final()
change to:
if (!A) return
if (!B) return
if (!C) return
final()
In your case instead of returning you could throw an exception.
try {
validateAndCreateNewUser();
}
catch(ValidationError $e) {
display($e->getMessage());
}
You don't need the empty checks at that point, move them to the validation functions.
For example:
function validate_email($str) {
if(empty($str)) {
return false;
}
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
$email = validate_email($_POST['email']);
if($email) {
// your code
}
This is a bit cleaner:
function validate_email($str) {
if (empty($str)) return false;
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
function validate_password($str) {
if (empty($str)) return false;
$str = trim($str);
if(strlen($str) < 5 || strlen($str) > 70) {
return false;
} else {
return $str;
}
}
$email = false;
$password = false;
$errorMessage = false;
$email = validate_email($_POST['email']);
if($email) {
$password = validate_password($_POST['password']);
if($password) {
createNewUser($email,$password);
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "Email address is invalid";
}
if($errorMessage) echo $errorMessage;
I have this If statement to check user submitted data. The data is first turned into an array which is then passed to a function where this if statement is located.
$errCount = 0;
$errMSG ='';
// Check Name
if ($submitData['FullName'] != '') {
if (strlen ($submitData['FullName']) < 4) {
$errCount + 1;
$errMSG .='The Full Name was too short!';
}
} else {
$errCount + 1;
$errMSG .='The Full Name Field was left blank!';
}
When this is run, even with an empty string, none of the errors are being triggered.
Am I missing something?
Thanks!
You are not assigning values to $errCount varaible when incrementing it;
$errCount = 0;
$errMSG ='';
$submitData['FullName']='';
// Check Name
if ($submitData['FullName'] != '') {
if (strlen ($submitData['FullName']) < 4) {
$errCount=$errCount + 1; // or u can write $errCount++;
$errMSG .='The Full Name was too short!';
}
} else {
$errCount=$errCount + 1; // or u can write $errCount++;
$errMSG .='The Full Name Field was left blank!';
}
echo $errMSG;
echo $errCount;
This will work.....
$errCount = 0;
$errMSG ='';
// Check Name
if(isset($submitData['FullName']) && strlen ($submitData['FullName'])>0 && strlen ($submitData['FullName'])<4)
{
$errCount++;
$errMSG .='The Full Name was too short!';
}
else if($submitData['FullName'] == '')
{
$errCount++;
$errMSG .='The Full Name Field was left blank!';
}
else
{
//success
}
When the row['error'] is bigger than 35, the value isn't present and the result of the function is 0. Where is the problem?
<?php
if ($row['error'] == "")
{
$error = "0";
}
else
{
$error = $row['error'];
}
if ($row['error'] != "")
{
if (strlen($error) > 35)
{
$error = substr($row['error'],0,32) + "...";
}
else
{
$error = $row['error'];
}
}
?>
Change
$error = substr($row['error'],0,32) + "...";
to:
$error = substr($row['error'],0,32) . "...";
The concatenate operator in PHP isn't a plus (+) sign; it's a period (.) sign
All this code is not necessary. The second condition is redundant, and it doubles the else condition from the above. Make it all with just these few lines of code:
<?php
$error = $row['error'];
if (strlen($error) > 35) {
$error = substr($row['error'],0,32) . "...";
}
?>
Because you check:
if(strlen($error) > 35) {
}
What am i doing wrong here? The username string is less than 2 chars but it still dont set error[]?
Register:
$errors = array();
$username = "l";
validate_username($username);
if (empty($errors)) {
echo "nothing wrong here, inserting...";
}
if (!empty($errors)) {
foreach ($errors as $cur_error)
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
function validate_username($username) {
$errors = array();
if (strlen($username) < 2)
$errors[] = "Username too short";
else if (strlen($username) > 25)
$errors[] = "Username too long";
return $errors;
}
It's because you are not assigning the return value of validate_username() to any variable.
Try
$errors = validate_username($username);
Change validate_username($username); to $errors = validate_username($username);
Your function is affecting a local variable named errors, not the global errors that you may have been expecting.
Further, your code can be cleaned up a little bit as follows
$username = "l";
$errors = validate_username($username);
// No errors
if ( empty($errors) ) {
echo "nothing wrong here, inserting...";
}
// Errors are present
else {
foreach ( $errors as $cur_error ) {
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
}
function validate_username($username) {
$errors = array();
$len = strlen($username);
if ( $len < 2 ) {
$errors[] = "Username too short";
} elseif ( $len > 25 ) {
$errors[] = "Username too long";
}
return $errors;
}
you're not returning it the right way, you need:
$errors = validate_username($username)
you forgot to assign $errors
$errors = validate_username($username);
**//TRY THIS INSTEAD**
$errors = array();
$username = "l";
**$errors = validate_username($username);**
if (empty($errors)) {
echo "nothing wrong here, inserting...";
}
if (!empty($errors)) {
foreach ($errors as $cur_error)
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
function validate_username($username) {
$errors = array();
if (strlen($username) < 2)
$errors[] = "Username too short";
else if (strlen($username) > 25)
$errors[] = "Username too long";
return $errors;
}