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.
Related
I have am trying to re-create a form register validation that I seen a few weeks ago but unable to figure it out.
I want to perform one last check after the first 3 checks then display the message
validation code
public function validateSignup(): bool
{
$this->errors = [];
if (empty($this->name) || (strlen($this->name) < 4)) {
$this->errors['name'] = "Username must be at least 4 characters.";
}
if (empty($this->email) || (filter_var($this->email, FILTER_VALIDATE_EMAIL) === false)) {
$this->errors['email'] = "Email address is required.";
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = "Password is required.";
}
return empty($this->errors);
}
This works great for the validation requirements but I want to add another step, to check if email or username is taken, I know how to do this traditionally but wanted to make it different without giving information away.
I have a Helper to tell me if an email is in the database called alreadyExists
what I am trying to accomplish is a 2nd check after that
Example
public function validateSignup(): bool
{
$this->errors = [];
if (empty($this->name) || (strlen($this->name) < 4)) {
$this->errors['name'] = "Username must be at least 4 characters.";
}
if (empty($this->email) || (filter_var($this->email, FILTER_VALIDATE_EMAIL) === false)) {
$this->errors['email'] = "Email address is required.";
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = "Password is required.";
}
return empty($this->errors);
## after it checks validation with no errors check if already exists
if ($this->name) Helpers::alreadyExists("user", "name", $this->name) {
$this->errors['name'] = "Unable to register user with provided data.";
}
return $this->errors;
}
public function validateSignup(): bool {
$this->errors = [];
if (empty($this->name) || (strlen($this->name) < 4)) {
$this->errors['name'] = "Username must be at least 4 characters.";
}
if (empty($this->email) || (filter_var($this->email, FILTER_VALIDATE_EMAIL) === false)) {
$this->errors['email'] = "Email address is required.";
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = "Password is required.";
}
If(count($this->errors) > 0) {
return empty($this->errors);
}
## after it checks validation with no errors check if already exists
if ($this->name) Helpers::alreadyExists("user", "name", $this->name) {
$this->errors['name'] = "Unable to register user with provided data.";
}
return empty($this->errors);
}
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'];
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {
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.
I want to refactor this piece of code, it takes input from a form, then sanitizes the input, then it checks if its empty, or too short. It does this for title, content and tags. It stores an errors encountered in an array called errors.
I want to make a function, something like this:
function validate_input($args)
Except I'm unsure as to how I'm going to implement it, and how it'll build up an error list.
(I know I can use something like PEAR QUICKFORM or php-form-builder-class, so please don't mention 'oh use Class xyz').
$title = filter_input(INPUT_POST, 'thread_title', FILTER_SANITIZE_STRING,
array('flags' => FILTER_FLAG_STRIP_HIGH|FILTER_FLAG_STRIP_LOW ));
$content = filter_input(INPUT_POST, 'thread_content');
$tags = filter_input(INPUT_POST, 'thread_tags');
# title here:
if (is_null($title) || $title == "") # is_null on its own returns false for some reason
{
$errors['title'] = "Title is required.";
}
elseif ($title === false)
{
$errors['title'] = "Title is invalid.";
}
elseif (strlen($title) < 15)
{
$errors['title'] = "Title is too short, minimum is 15 characters (40 chars max).";
}
elseif (strlen($title) > 80 )
{
$errors['title'] = "Title is too long, maximum is 80 characters.";
}
# content starts here:
if (is_null($content) || $content == "")
{
$errors['content'] = "Content is required.";
}
elseif ($content === false)
{
$errors['content'] = "Content is invalid.";
}
elseif (strlen($content) < 40)
{
$errors['content'] = "Content is too short, minimum is 40 characters."; # TODO: change all min char amounts
}
elseif (strlen($content) > 800)
{
$errors['content'] = "Content is too long, maximum is 800 characters.";
}
# tags go here:
if (is_null($tags) || $tags == "")
{
$errors['tags'] = "Tags are required.";
}
elseif ($title === false)
{
$errors['tags'] = "Content is invalid.";
}
elseif (strlen($tags) < 3)
{
$errors['tags'] = "Atleast one tag is required, 3 characters long.";
}
var_dump($errors);
Should be pretty simple if understood your problem correctly and you want to validate and sanitize only those three variables.
function validateAndSanitizeInput(Array $args, Array &$errors) {
//validation goes in here
return $args;
}
In this case the errors array is passed by reference so you'll be able to get the error messages from it after the function has been called.
$errors = array();
$values = validateAndSanitizeInput($_POST, $errors);
//print $errors if not empty etc.
By the way you could replace "is_null($content) || $content == """ with "empty($content)"