preg_matchvalidation - php

Okay, everything I've checked on this site referring to validation isn't what I'm looking for.
What I'm looking to do is a minimum length and maximum length of a value in firstname and secondname, this is the code which I currently have.
if (isset($_POST['submit'])) {
$errors = array();
if (isset($_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "You have not entered a first name";
}
if (isset($_POST['secondname'])) {
$sn = $_POST['secondname'];
} else {
$errors[] = "You have not entered a second name";
}
I was just wondering how would I apply preg_match to those which the minimum is 4 letters and the maximum is 15?
I do know it's something to do with
if(preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname']))
In doing this I tried to do
if (isset($_POST['firstname']) && preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname')) {
But that also gave me an error :/
Could anyone give me a solution for this?
Thanks!
UPDATE:-
Nvm, I found a way around it. I just did this
if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3> You must enter between 4 and 15 characters! </h3></center>";
}
} else {
$errors[] = "You have not entered a name";
}
For both the firstname and secondname. :)

Why don't you just use strlen() to get the string length, and then test it against your limits ?
$length = strlen($nick);
if ($length > 3 AND $length < 16) {
//Do STuff
} else {
//Do stuff for failed requirement
}

I found a way around it. I just did this
if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3>You must enter between 4 and 15 characters!</h3> </center>";
}
} else {
$errors[] = "You have not entered a name";
}
For both the firstname and secondname.

Related

Variable always being set to 0 despite conditional blocks

The following block of code is an attempt to give some feedback for what a user may be inputting incorrectly and that side of it is working alright.
The part I am having trouble with is the else block. It seems to always set the $MaxNum variable to 0. If I remove the declaration from the else block it works fine, although obviously doesn't allow my code above to validate the input. I am probably overlooking something quite basic so any help would be great.
global $MaxNum, $TheNum;
if (isset($_POST['Submit'])) {
if (empty($_POST['maxnum'])){
$error[] = "<p>Please enter at least something!";
if($_POST['maxnum'] == 0){
$error[] = "<p>Zero doesn't count!";
}
}
if (!is_numeric($_POST['maxnum'])){
$error[] = "<p>You didn't enter a number!";
}
if (is_numeric($_POST['maxnum'])){
if(($_POST['maxnum'])>2147483647){
$error[] = "<p>2.14 Billion jellybeans is a little excessive, right?";
}
}
else{
$MaxNum = $_POST['maxnum'];
}
}
Some tips:
Try to use functions and early returns in your code, it makes your flow easier.
Try to use less nested if statements and use else if
An example with function and early returns:
global $MaxNum, $TheNum;
function handleFormSubmit(): string
{
if (!isset($_POST['Submit']) || !isset($_POST['maxnum'])) {
return "<p>Please enter at least something!</p>";
}
if(empty(['maxnum'])) {
return "<p>Please fill in a number</p>!";
}
if($_POST['maxnum'] == 0) {
return "<p>Zero doesn't count</p>!";
}
if (!is_numeric($_POST['maxnum'])) {
return "<p>You didn't enter a number!";
}
if (is_numeric($_POST['maxnum']) && $_POST['maxnum'] > 2147483647) {
return "<p>2.14 Billion jellybeans is a little excessive, right?";
}
$MaxNum = $_POST['maxnum'];
return '';
}
$errorMessage = handleFormSubmit();
Used #robbert van den Bogerd's tips to clean up my if statements and then implemented that. Still had the issue of the input being passed as there was nothing stopping that.
Created a new variable called $ValidInput and used it to hold a bool.
Through the checking I set it to False if it met any conditions.
Then at the end of the checks I attach the input to $MaxNum if $ValidInput remains True through the checking, if it made it to that point and was True it must meet our requirements.
global $MaxNum, $TheNum, $ValidInput;
$ValidInput = True;
if (isset($_POST['Submit'])) {
if (empty($_POST['maxnum'])) {
$error[] = "<p>Please enter at least something!</p>";
$ValidInput = False;
}
if(empty($_POST['maxnum']) && (!is_numeric($_POST['maxnum']))) {
$error[] = "<p>Please enter a number!</p>";
$ValidInput = False;
}
if($_POST['maxnum'] == 0) {
$error[] = "<p>Zero doesn't count!</p>";
$ValidInput = False;
}
if (!is_numeric($_POST['maxnum']) && (!empty($_POST['maxnum']))) {
$error[] = "<p>That's not a number!</p>";
$ValidInput = False;
}
if (is_numeric($_POST['maxnum']) && $_POST['maxnum'] > 2147483647) {
$error[] = "<p>Anything over 2.14 Billion jellybeans is a little excessive, right?";
$ValidInput = False;
}
if($ValidInput == True){
$MaxNum = $_POST['maxnum'];
}
}

PHP show full list of errors in a array

I use OOP and i wanted to ask you guys how this would be done! I keep trying but its still not working ;(
Here is my class file:
class Signup {
// Error
public $error = array();
public function validate($username, $email_mobile, $password) {
if(!empty($username) || !empty($email_mobile) || !empty($password)){
if(strlen($username) < 3 || strlen($username) > 50){
$this->error = "Username is too short or too long!";
return $this->error;
}elseif(strlen($email_mobile) < 3 || strlen($email_mobile) > 50) {
$this->error = "Email is too short or too long!";
return $this->error;
}elseif(strlen($password) < 3 || strlen($password) > 50){
$this->error = "Password is too short or too long!";
return $this->error;
}
} else {
$this->error = "Please fill are required feilds";
return $this->error;
}
}
Here is my signup file
$error[] = $signup->validate($username, $email_mobile, $password);
<?php
// require('lib/function/signup.php');
if(isset($error)){
var_dump($error);
foreach ($error as $value) {
echo $value . "<br>";
}
}
?>
I know That im calling the $error in the same file and not the property error. But i dont know how to send this array to the other file! Please help me! Also i have Called everything and the problem is just with my code(i think), i only included my file and made a var to call my signup class
It is never too early in your development career to study coding standards. Jump straight to PSR-12, and adopt all of these guidelines to write beautiful, professional code.
Use data type declarations in your classes where possible, it will improve the data integrity throughout your project(s).
You appear to prefer returning an array of errors. For this reason, I see no benefit in caching the errors long-term in a class property. This coding style is fine to do, but you could choose to return nothing (void) and instead populate a class property $errors, then access it directly after the $signup->validate() call via $signup->errors or use a getter method.
The empty() checks are too late in the flow. Once the values have been passed to the class method, these values must already be declared. For this reason empty() is needless overhead to check for mere "falsiness". Just check the values' string length.
Your data quality checks seem a little immature (email and password checks should be much more complex), but I won't confuse you with any new complexity, but I do expect that your validation rules will increase as you realize that users cannot be trusted to put good values in forms without be forced to do so. For this reason, it is probably unwise to use a loop to check the value lengths because you will eventually need to write individual rules for certain values.
A possible write up:
class Signup
{
public function validate(
string $username,
string $email,
string $password
): array
{
$errors = [];
$usernameLength = strlen($username);
if ($usernameLength < 3 || $usernameLength > 50) {
$errors[] = "Username must be between 3 and 50 characters";
}
$emailLength = strlen($email);
if ($emailLength < 3 || $emailLength > 50) {
$errors[] = "Email must be between 3 and 50 characters";
}
$passwordLength = strlen($password);
if ($passwordLength < 3 || $passwordLength > 50) {
$errors[] = "Password must be between 3 and 50 characters";
}
return $errors;
}
}
When calling this method...
$signup = new Signup();
$errors = $signup->validate(
$_POST['username'] ?? '',
$_POST['email'] ?? '',
$_POST['password'] ?? ''
);
if ($errors) {
echo '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
} else {
echo 'No errors';
}
You should add elements to the array, instead of overwriting it, and returning, on all the branches.
class Signup {
public $errors = [];
public function validate($username, $email_mobile, $password) {
if (empty($username)) {
$this->error[] = "Username cannot be empty";
} else {
$strlenUsername = strlen($username);
if ($strlenUsername < 3 || $strlenUsername > 50){
$this->errors[] = "Username is too short or too long!";
}
}
if (empty($email_mobile)) {
$this->error[] = "Email cannot be empty";
} else {
$strlenEM = strlen($email_mobile);
if ($strlenEM < 3 || $strlenEM > 50) {
$this->errors[] = "Email is too short or too long!";
}
}
if (empty($password)) {
$this->errors[] = "Password cannot be empty";
} else {
$strlenPass = strlen($password);
if ($strlenPass < 3 || $strlenPass > 50) {
$this->errors[] = "Password is too short or too long!";
}
}
return $this->errors;
}
}
If you always keep the same constrains for the three fields, you can shorten it:
class Signup {
public function validate($username, $email_mobile, $password) {
$errors = [];
$fields = [
'Username' => $username,
'Email' => $email_mobile,
'Password' => $password
];
foreach($fields as $key => $value) {
if (empty($value)) {
$errors[] = "$key cannot be empty";
} else {
$strlen = strlen($value);
if ($strlen < 3 || $strlen > 50) {
$errors[] = "$key is too short or too long!";
}
}
}
return $errors;
}
}
The above code guesses at what you are trying to do, if you just wanted a fix for not getting any results on $error see the original answer below.
Original answer.
Updating your code to this should give you the results you expect.
class Signup {
// Error
public $error = array();
public function validate($username, $email_mobile, $password) {
if (!empty($username) || !empty($email_mobile) || !empty($password)){
$strlenUsername = strlen($username);
$strlenEM = strlen($email_mobile);
$strlenPass = strlen($password);
if ($strlenUsername < 3 || $strlenUsername > 50){
$this->error[] = "Username is too short or too long!";
} elseif ($strlenEM < 3 || $strlenEM > 50) {
$this->error[] = "Email is too short or too long!";
} elseif ($strlenPass < 3 || $strlenPass > 50){
$this->error[] = "Password is too short or too long!";
}
} else {
$this->error[] = "Please fill are required feilds";
}
return $this->error;
}
}
Keep in mind that, since you are using if-else you will always have, at most, one element in the array, it is hard to tell what you are trying to do with certainty, so I didn't change the logic and just fixed the most obvious problem.
If you want to add error messages to the array, get rid of the else keyword on the conditionals.
If you want to only receive one error message, consider using a string instead of an array.

How to edit id code value in php

I am using the code bellow in a formmail. But i want to change the code, so user input can be both numbers and letter and others, and so it can be any lenght. Hope someone can help with the 2 changes. Thanks.
if(isset($_POST['idcode'])) {
if(strlen($_POST['idcode']) != 8 || !is_numeric($_POST['idcode'])) {
$error = "input must contain 8 numbers";
} else {
If you want to make it accepts everything do this:
if(isset($_POST['idcode'])) {
// code here
} else {
$error = "you must set the idcode"; // can be changed
}
But if you want to check for length of 8 and up do this:
if(isset($_POST['idcode'])) {
if(strlen($_POST['idcode']) >= 8) {
// code here
} else {
$error = "you need to have at least 8 chars"; // can change
}
} else {
$error = "you must set the idcode"; // can be changed
}

PHP - Check if one of two form fields is filled?

My form has Phone and Email fields.
Many people might not be wanting/able to put both,
so I thought, that the validator would require only
one of those two filled, instead of requiring the both filled.
I've tried thinking of different ways to do it but I'm pretty new to PHP,
so I couldn't come with any.
Would this be possible?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["phone"]))
{$phone = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
}
Thank you.
As your title states, 1 / 2 form fields is filled in.
$i = 0; // PUT THIS BEFORE YOUR IF STATEMENTS
Inside of your statements:
if (empty($_POST["phone"])) {
$phone = "";
} else {
$i++; // PUT THIS IN ALL YOU WANT TO COUNT, IT WILL ADD 1 to $i EACH TIME YOU CALL IT
$website = test_input($_POST["website"]);
}
Now at the end, if
// YOU NEED TO CHANGE YOUR NUMBERS TO WHATEVER COUNT YOU WANT
if ($i < 2) { // IF $i IS LESS THAN 2
// YOUR CODE HERE
} else { // IF $i IS 2 OR MORE
// YOUR CODE HERE
}
Hope this is somewhat useful!
or as stated above, you can use an
if (#$A && #$B) { // REQUIRES BOTH TO BE TRUE
// YOUR CODE HERE
} elseif (#$A || #$B) { // REQUIRES ONLY ONE TO BE TRUE
// YOUR CODE HERE
} else { // NONE ARE TRUE
// YOUR CODE HERE
}
if you are wondering about the # signs above, they are simply checking if they are set, you could change the code to !empty($A) which is what you used above. Putting the ! before the empty function checks that it is false or that $A is actually set.
If i would have to check a form like you, i'd do it this way:
$res = '';
if(empty($_POST['name']))
$res .= 'The name is required.<br>';
if(empty($_POST['email']))
$res .= 'The email is required.<br>';
if(empty($_POST['phone']) && empty($_POST['email']))
$res .= 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo 'We have these errors:';
echo $res;
}
else {
echo 'No Errors!';
}
If you want to show only one error each time, use this code:
$res = '';
if(empty($_POST['name']))
$res = 'The name is required.<br>';
elseif(empty($_POST['email']))
$res = 'The email is required.<br>';
elseif(empty($_POST['phone']) && empty($_POST['email']))
$res = 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo $res;
}
else {
echo 'No Error!';
}
Even if i think it's very basic, i'll explain the mentioned part, even if you could look it up from php.net:
$res .= 'The name is required';
The ".=" operator adds the part 'The name is required' to the variable $res. If this happens the first time, the variable will be empty, because i initialized it as an empty string. With every ongoing line, another error Message will be added to the string.
if(strlen($res) > 0) {
strlen() will return the length of the string in $res. If no error occured, it would still be empty, so strlen() would return 0.

how to restrict the value entered in a textbox based on the value entered in the previous one in php

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

Categories