PHP validation function. Check for numeric and positive - php

Little confused about how to code this. User inputs numbers, then the validation checks to make sure it is numeric and positive. The user can also leave this field blank.
This is what i have so far, it just checks to see that something was inserted.
$error_blue = check_blue($phone);
if($error_blue !=''){
print "<p>Blue: $error_blue";
}
Is where the item is validated at the top of the page.
function check_blue($blue){
if(! is_numeric($blue)){
return'Please Enter a valid number for Blue.';
}}
Is where the function is.
Any help on what to do here would be much appriciated.

Something like this?
function check_blue($blue) {
if (is_numeric($blue) && $blue > -1) {
return 1;
}
else {
return 0;
}
}
if(!check_blue($phone)) {
return'Please Enter a valid number for Blue.';
}
See the demo

Assuming it's an integer you expect,
if ((int)$blue==abs($blue) || empty($blue)) $error = false;
else $error = true;
Then you use $error to decide what to do.

Everyone here was using if else. It is not that this is wrong, but just to show you another idea, which might be useful for other type of validation, take a look at validate filters :
http://www.php.net/manual/en/filter.filters.validate.php
For this purpose you might use FILTER_VALIDATE_INT

You might want to use something simple as
function check_blue($phone) {
return (empty($phone) || (is_numeric($phone) && $phone >= 0));
}
First check if the field is blank, nothing to do if it is.
If it is not blank it will be checked for numericality and to being greater or equal zero.

Related

Tricky verification code on a form

I have an implemented control check on a form coded this way:
public function checkCittaResidenza() {
if (is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45 || strlen($this->citta_residenza == 0))) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
}
In this version, it simply checks if it is a string and check its lenght that should be less than 45 chars. It puts the string in an array corretti() if positive, else it initialize an error message specified above in an abstract class parent of the checking class.
What i'd love it to do is:
1) make a check on the string to see if it's not null.
2) if it's not null, do the check (that could be even more particular than the simple one shown here, but i don't have problems on this), put it in corretti() if correct and initializing the error if it's not, as the code now says.
3) if the string is null, the program should skip the check and directly write the null value into the array corretti(), because the form is imagined to be completed in different steps over the time, so it always happen that it's not fully filled.
I'm having problem on coding the if cycle for this last condition, every cycle i tried and imagined puts the empty condition as a cause for initializing an error.
Thank you!
Try this,
public function checkCittaResidenza() {
if(isset($this->citta_residenza)){
if ((is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45) || $this->citta_residenza == "")) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
} else {
$this->corretti['citta_residenza'] = "null";
}
}

Validate Integer in Form Input Using is_numeric

In my form, a team's score is input, validated by the PHP script and then passed to the MySQL database. However, I want to make sure that a positive integer is being submitted, so there are no problems on the back-end when league standings are tabulated.
Research led me to the conclusion that using is_numeric would be the best way to go about this. However, it fails to recognize zero as an integer and that presents a problem for me. When I echo it in an array by itself, it shows as true, but something about the way I've written it in the script is not working.
I tried converting the $_POST with intval first and then processing the number with is_numeric, but that doesn't seem to help. Here's the code:
// Validate the away score:
if (empty($_POST['away_score'])) {
echo "You forgot to enter the away score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['away_score'])) {
echo "You entered an invalid score for the away team.<br>";
$validate = 'false';
} else {
$away_score_value = mysqli_real_escape_string($db, trim($_POST['away_score']));
$validate = 'true';
}
Any thoughts?
The string '0' is not truthy. That means that anything that checks it in a boolean'ish manner will treat it as false. In particular, empty($_POST['away_score']) will evaluate to true, so is_numeric would never even get a chance to fail.
Short version: empty is too wishy-washy in this case. Check for null and '' explicitly.
if (!isset($_POST['away_score']) or $_POST['away_score'] == '') {
You could use built-in validation. Explore few examples from Validation examples. And read about filter_input.
For example.
var_dump(filter_input(INPUT_POST, 'score', FILTER_VALIDATE_INT, array(
'options' => array(
'min_range' => 1,
'max_range' => 5,
)
)));
P.S. use prepared statements.
ctype_digit( (string) $score);
preg_match('#^\d+$#', $score);
In b4 #EmilioGort
boolean false
int 0
<?php
try {
// Check if user submitted "away_score" with valid form.
// "away_score" can be UNDEFINED or STRING or ARRAY.
if (!isset($_POST['away_score']) || !is_string($away_score = $_POST['away_score'])) {
throw new RuntimeException('You cannot access without valid form submitting.');
}
// If "away_score" is not filled in, this will be EMPTY STRING.
if ($away_score === '') {
throw new RuntimeException('You forgot to enter the away score.');
}
// Check if trimmed "away_score" has only digits.
if (!ctype_digit($away_score = trim($away_score))) {
throw new RuntimeException('You entered an invalid score for the away team.');
}
// do something
} catch (Exception $e) {
printf("<p>%s</p>\n", $e->getMessage());
}
Using regex
if (preg_match('/\A\d++\z/', $variable)){//including 0
//do somthing
}else{
echo "This is not a Positive Integer"
}
is_numeric(4.2) return true with float
is_int(2) return false if the data are obtained using supergloblals like $_POST or $_GET
} elseif (!preg_match('/^([0-9]+)$/', $_POST['away_score'], $m)) {
$AwayScore = $m[1]; # $AwayScore to go to mysql
echo 'not numeric!';
$valid = false;
}
This just works!
preg_match() works for any type, including integer/long/float, anything!
But using is_numeric is the proper way of checking whether a given input is or not a number in PHP, and
var_dump(is_numeric(0));
should return bool(true). Have you tried is_int instead?
elseif (!is_numeric(POST[$_'$away_score']) && !is_null(POST[$_'$away_score']))
Because 0 (or null) is not a numeric value, you have to check if the score isn't null.

Modulus of a string

I am in a very puzzling situation. Intially when an user visits a particular page, a popup is shown. User can accept it or decline it. When a user declines it, after 5 page visits, the pop up is again shown to user. This part is working perfectly. When user clicks ok, an ajax call is made and the SESSION variable is set to ok. Lets say initially $_SESSION['count'] = 0. I have two condition statements.
if($_SESSION['count']%5 === 0)
{ // do something
}
elseif($_SESSION['count'] === "ok")
{ // do something
}
Now when an user press ok, an ajax call is made updating $_SESSION['count'] = "ok".
When the user again reloads the page, condition if($_SESSION['count']%5 === 0) gets true even though $_SESSION['count'] is now ok. Later after much experimenting, i came to know that in php i am able to divide or find modulus string by number which will result in zero. How can i handle this?
You can use is_numeric to check if it is a count or 'ok'
http://php.net/manual/en/function.is-numeric.php
if(is_numeric($_SESSION['count']) && $_SESSION['count']%5 === 0)
{ // do something
}
elseif($_SESSION['count'] === "ok")
{ // do something
}
Though generally, I would set ok to be the value of a different variable in $_SESSION as a best practice. If I was looking at the code I would find it very odd to see something called count having a string value.
PHP is very good at implicit casting.
A solution to your issue is simply re-arrange your if else tree.
if($_SESSION['count'] === "ok")
{
// do something
}
elseif($_SESSION['count'] % 5 === 0)
{
// do something
}
Readability
Something to bare in mind, is that a variable count should really contain a value. Perhaps using a different variable might make your code a little less confusing to a reader.
In php, (int) "some string" == 0, so check if $_SESSION['count'] is an integer (e.g. using is_numeric()) before doing the modulus.
Check this working example. It may help:
if(!isset($_SESSION['foo'])) {
$_SESSION['foo'] = 0;
} else {
$_SESSION['foo']++;
}
var_dump($_SESSION['foo']%3);
if(is_numeric($_SESSION['count']) AND $_SESSION['count']%5 === 0)
{ // do something
}
elseif($_SESSION['count'] === "ok")
{ // do something
}

PHP Logic - Return False of one or two out of three are not set

I have a form that collects information, one piece of which is a phone number. The phone number data comes from three fields, one for an area code, for the first 3 digits, and for the last four, so that numbers are in this format: xxx-xxx-xxxx (basic U.S. format).
These three fields are not required, but I would like to do some basic error checking if someone decides to fill out any combination of the three field:
(let's say they only give me the area code - that means that they wanted to give me their number, so in essence, it becomes required, so the code should check to see that 1) all three data sets were sent, and 2) all three are only numbers)
Here is what I thought would work, but it does not:
if((isset($_POST['numArea'], $_POST['numFirst'], $_POST['numSecond']) && (!ctype_digit(trim($_POST['numArea'])) || !ctype_digit(trim($_POST['numFirst'])) || !ctype_digit(trim($_POST['numSecond'])) || strlen(trim($_POST['numArea'])) !== 3 || strlen(trim($_POST['numFirst'])) !== 3 || strlen(trim($_POST['numSecond'])) !== 4))
|| (isset($_POST['numArea']) XOR isset($_POST['numFirst']) XOR isset($_POST['numArea']))){
$errors[] = 'Please give us a valid Phone Number, or remove any numbers if you do not wish to use your phone number.';
}else{
$_POST['PhoneNumber'] = '+01'.$_POST['numArea'].'-'.$_POST['numFirst'].'-'.$_POST['numSecond']; }
Any suggestions?
The reason why your code isn't working is not because of your boolean logic, but because of your use of isset(). In the case of a <input type="text">, the $_POST['fieldName'] will always be set, regardless of if the value is empty or not.
Use $_POST['fieldName'] != '' instead to determine if the user has entered a value. DO NOT USE empty(), as this will return any falsy value as empty (0, 000, false, etc...).
Personally, I rather use one <input type="type"> for the phone number. This is less annoying than making the user switch boxes, and also makes validation simpler.
This example actually validates if the number follows NANP rules. I find it absolutely ridiculous that so many applications/websites oversees this validation step.
// Did the user post a number?
if($_POST['phone'] != '') {
// Get only the numbers, we don't care how the user formatted their number
$_POST['phone'] = preg_replace('/[^0-9]/', '', $_POST['phone']);
// Is it a valid NANP phone number?
if(preg_match('/^1?[2-9][0-8][0-9][2-9][0-9]{6}$/i', $_POST['phone']) === 1) {
echo "Valid NANP phone number";
// Trim the leading one
$_POST['phone'] = ltrim($_POST['phone'], '1');
// Format as wanted
$_POST['PhoneNumber'] = '+01'.substr($_POST['phone'],0,3).'-'.substr($_POST['phone'],3,3).'-'.substr($_POST['phone'],6,4);
} else {
echo "Invalid phone number";
}
} else {
echo "User didn't provide phone number";
}
First of all if those fields are inputs then isset() will always return true. What you probably want to check is if they are not empty. So you should use empty() function for that.
I will replace your form values with $a, $b and $c to make it simple.
$a = $_POST['numArea'];
$b = $_POST['numFirst'];
$c = $_POST['numSecond'];
if (!empty($a) || !empty($b) || !empty($b)) {
// we know now that at least field was filled in, lets check their values
$regex = '/^\d+$/';
if (!preg_match($regex, $a) || !preg_match($regex, $b) || !preg_match($regex, $c)) {
echo "Phone number invalid";
}
}
This is just an example. You could shorten it to just one if statement but I haven't done so to make it more readable.
Just check if one of the fields is not set;
if (!isset($_REQUEST['numFirst']) || !isset($_REQUEST['numSecond']) || !isset($_REQUEST['numArea'])) {
if (!isset($_REQUEST['numFirst'])) {
print 'Please fill out the FIrst area';
}
if (!isset($_REQUEST['numSecond'])) {
print 'Please fill out the Second area';
}
if (!isset($_REQUEST['numArea'])) {
print 'Please fill out the Area code';
}
}
Is that the kind of thing you wanted to do?
This is not solution for your problem , but it will solve it other-way , try imask
it's actually a JS script .
Well first off, if anyone is ever gonna be able to maintain your code, you'll have to break that up into method calls. I'd probably write it something like this:
public function phoneNumberWasProvided () {
return !(empty($_POST['numArea']) &&
empty($_POST['numFirst']) &&
empty($_POST['numSecond']));
}
public function phoneNumberIsValid () {
$this->_phoneErrors = array();
// The following three if statements can also be
// extracted into their own methods
if(!preg_match("/^\d{3}/$", $_POST['numArea']) {
$this->_phoneErrors['numArea'] = 'The area code you provided is invalid';
}
if(!preg_match("/^\d{3}/$", $_POST['numFirst']) {
$this->_phoneErrors['numFirst'] = 'The first part of the provided phone
number is invalid';
}
if(!preg_match("/^\d{4}/$",$_POST['numSecond']) {
$this->_phoneErrors['numArea'] = 'The first part of the provided phone
number is invalid';
}
return empty($this->_phoneErrors);
}
Now you can easily use these methods inside your main logic, making it more readable:
if($this->phoneNumberWasProvided()) {
if(!$this->phoneNumberIsValid()) {
$errors = $this->getPhoneNumberErrors();
// Print errors / do whatever is necessary
} else {
$phoneNumber =
"{$_POST['numArea']}-{$_POST['numFirst']}-{$_POST['numSecond']}";
}
}

consecutive if's in PHP

I'm doing some validation now in PHP, and I'm running allot of conditional statements, for example:
if ($this->email->isValid($email))
return false;
if ($this->username->isValid($username))
return false;
ect..
Is there a nice way to do this? Or do I just run ten If statements like the ones above?
I can't use switch obviously, but I'm looking for that type of solution..
P.S... I'm using Zend Framework for validation
You could OR them like this:
if(cond1||
cond2||
cond3||
cond4)
{
return false;
}
Doing something like this is called a Guardian clause. It can be improved so clauses that return the same value should be grouped together.
if ($this->email->isValid($email) || $this->username->isValid($username))
{
return false;
}
Or like this, if there are many (btw how I format the if is just so it can read better, any other way should be fine as well)
if (
$this->email->isValid($email) ||
$this->username->isValid($username) ||
$this->somethingelse()
)
{
return false;
}
If this is data from a form, take a look at Zend_Form, as recommended by a poster in your other question
I posted some example code which details adding validators to form elements
Just make sure that you put the most obvious validation at the top, so if its going to fail it will trip before it runs through every statement. Also, I don't like if statements without curly brackets, but then thats just a matter of opinion.
if ($this->email->isValid($email) ||
$this->username->isValid($username))
return false;
It is always good to use some var than multiple returns
In case these are the only return conditions. We dont need to check for all conditions. like check only for true conditions return false by default or vice-versa.
$result = false; //return false by default.
if (cond1 || cond2) { //check only for conditions which result in returning true. :)
$result = true;
}
return $result;
Cheers,
-Ratnesh
I would make them data members of my class. Obviously here you will have to have a form driven class. So here for example the email could be wrapped into a class and initialised with in the constructor of the class that has them as member variables. Now the email wrapper class will do validation for email on initialisation/construction.
IMHO that would look less cluttered and you can wrap up any validation or specific methods to the email-wrapper class.
I know it might be a sledge hammer in some context; so choose wisely!
Maybe something like this:
foreach( $form->getElements as $element => $value )
{
if( !$element->isValid( sanitize($value))){
return false;
}
}
BUT if you are using ZF this is your oneliner answer because you check all the form in one not individual fields:
$form = new My_Zend_Form(); // in the controller action that you send the form to
if ( $form->isValid($_POST)) {
// Success /// do whatever you want with the data
$data = $form->getValues();
} else {
//error
}
Do something like this:
$errlvl = 0;
if($errlvl == 0 && $this->email->isValid($email)){
$errlvl++;
}
if($errlvl == 0 && $this->username->isValid($username)){
$errlvl++;
}
// your validation list keeps going
if($errlvl > 0){
return false;
}
this will
Reduce redundancy because if there's an error in front, the following will not be checked.
you can keep adding on to the list
if you want to know how many errors occurred, you can remove $errlvl == 0 in the statements
Add all objects to an array and the iterate it (I guess you or Zend are using an interface "validator" or something like that each component (username, email, etc) implements the "isValid" method):
$validators = array();
$validators[] = $this->email;
$validators[] = $this->username;
foreach ($validators as $validator)
{
if (!$validator->isValid())
{
return false;
}
}

Categories