I have a sign up form with about 10 fields and they are all required to be filled in before processing, so trying to avoid all those if checks I came up with this, is this a good method?
foreach($list as $items) {
if(empty($items)) {
$error[] = "All fields are required.";
break;
}
}
or should I make if(empty($field_1) || empty($field_2) etc.. then output the error?
Assuming that your data is coming from $_GET or $_POST, all data fields will be strings. This means that you should be able to do the check in a single function call:
if (in_array('', $list, TRUE)) {
$error[] = "All fields are required.";
}
This looks for strings which are exactly equal to an empty string. If you want to make the comparisons loose (more or less identical to the check that empty() does) just remove the final TRUE.
EDIT Thinking about it, you don't need the strict comparison. I did this to allow for a legitimate field value of '0' (which empty() would not allow) but this will also be permitted with loose comparisons, since '0' != ''.
ANOTHER EDIT If you want to check that the length of the sting is greater than two, you will have to loop:
foreach ($list as $item) {
if (strlen($item) < 2) {
$error[] = "All fields are required.";
break;
}
}
This will also "clear out 0" assuming that by this you mean "not allow a value to be 0". If you also want to disallow '00' (or any other string that results in 0) you can change the if clause to this:
if (strlen($item) < 2 || (!(int) $item)) {
it's ok. If you just want to show message "All fields are required." without showing which field in blank.
Otherwise it will be more user friendly if you check and show which field is left empty.
It's good idea to put it into loop as you did but please note that this will fail even when user inputs 0 and will pass for string containing only spaces, so you may want to make better checks than empty()
I would approach this with an in_array check.
<?php
$fields=array('name','age','yadayada','something_else');
foreach ($_POST as $key=>$value){
if(in_array($key,$fields) && $value!=''){
$$key=$value;
}else{
$error[$key]='This field is required.';
}
}
?>
Related
How to use PHP to check form field for specific value?
The value '7' would need to be inserted or else the form field will be invalid; so invalid with all other numbers then 7.
if(empty($_POST['captcha']))
{
$this->add_error("Did you solve the captcha?");
$ret = false;
}
Works to check if any value -- but I need to specify, must be 7.
if(strlen($_POST['captcha']) =!7) // tried this but form completely died or disappeared
{
$this->add_error("Did you solve the captcha?");
$ret = false;
}
There are two things to note here:
You shouldn't use empty() here, because "0" is considered empty as well and it seems like it could be the answer of an equation; use isset() instead to just check whether the value is part of the request.
You're trying to check the length of $_POST['captcha'] instead of comparing its value.
So:
if (!isset($_POST['captcha']) || $_POST['captcha'] != 7) {
$this->add_error('Did you solve the captcha?');
$ret = false;
}
You have two problems:
=! should be !=. See comparison operators.
if(strlen($_POST['captcha']) != 7)
You also need to turn on error reporting.
I have some questions about my server-side validation script.Currently, i validate my input data by checking if the fields in the $_POST array are empty, of if they are shorter than the min length.
My script(extract);
if(!isset($_POST['BizAddItemCat']) OR empty($_POST['BizAddItemCat']))
{
die("Please enter a category for your item.");
}
if(!isset($_POST['BizAddItemSubCat']) OR empty($_POST['BizAddItemSubCat']))
{
die("Please enter a subcategory for your item");
}
if(!isset($_POST['BizAddItemName']) OR empty($_POST['BizAddItemName']) OR strlen($_POST['BizAddItemName']) < 5)
{
die("Your item name must contain at least 5 characters");
}
if(!isset($_POST['BizAddItemPrice']) OR empty($_POST['BizAddItemPrice']))
{
die("Your item must have a price");
}
if(!isset($_POST['BizAddItemQty']) OR empty($_POST['BizAddItemQty']))
{
die("You must enter your available stock for your item");
}
if(!isset($_POST['BizAddItemDesc']) OR empty($_POST['BizAddItemDesc']) OR strlen($_POST['BizAddItemDesc']) < 20)
{
die("Your item description must contain at least 20 characters");
}
I then trim the $_POST variables and assign them to variables
$itemcat=trim($_POST['BizAddItemCat']);
$itemsubcat=trim($_POST['BizAddItemSubCat']);
$itemname=trim($_POST['BizAddItemName']);
$itemprice=trim($_POST['BizAddItemPrice']);
$itemqty=trim($_POST['BizAddItemQty']);
$itemdesc=trim($_POST['BizAddItemDesc']);
However, a string with all spaces (e.g " " ), will pass the empty() check but all the spaces will be removed by trim(). Therefore if i have a string with all spaces passed in, it would pass my validation and will have all the spaces removed, leaving me with an empty variable?
However, if i trim my variables before validating them, then i wouldn't be able to check if the fields exist (isset($_POST['etc'])?
If so, how would i go about addressing this?
You could either trim the value before it goes through the condition, or, change the condition to check for an empty string.
if ($_POST['whatevervalue'] !== " ")
I would suggest going with trimming before the condition. Although why you're assignment statements come after the checks is confusing me.
I would like to determine whether or not a variable has any text at all.
For instance, my current code is this:
if (is_numeric ($id))
{
//do stuff
}
else
{
// do other stuff
}
However, there is a problem if my variable contains both a string and a number
such as "you are 93 years old",
because it sees that number 93 is present and considers the variable numeric.
I want the if statement to only "do stuff" if there is absolutely no text in the variable at all.
Thanks
Try casting the value to int (or float) then compare it back to the unaltered version. They should match values (but not type)
if((int)$id == $id) {
} else {
}
another option would be to use preg_match("/^([\d.\-]+)$/", $id). This would allow you to be very specific about what characters you let $id contain. However using regexp should be considered as the final choice (for performance reasons)
if(empty($var) && $var !== "0" && $var !== 0) {
// it's really empty, not a string "0" and not a numeric 0
}
You could also check if it's not a boolean false for the sake of completeness.
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']}";
}
}
I am currently trying to validate a form server side, the way it works is all the data is put into and array, with the form field as the key and and the field data as the value, however I need to check that all the keys have a value associated with other wise I want the submittion to stop and the user having to edit there details and then re-submit, is there a quick check I can run rather that break the array apart and check that or check before it is put in the array with a switch or losts of if statements?
Sico87,
More of than not you don't want to test all of the fields simultaneously. For instance you may have a contact field that contains a phone-number entry option that isn't mandated, and rejecting the submission for that reason would be problematic.
In many cases, it's easier to test your fields individually so you can give each the special attention it needs. You'll want to give special attention to email addresses, and special attention to birthdays.
Treating all equal could cause very serious problems in the long-run.
function fieldEmpty($value) {
return trim($value) == '';
}
if (count(array_filter($array, 'fieldEmpty'))) {
die('bad');
}
One option is to do a bit of both.
Have a separate array of field options with the field name as the key.
$fieldTypes = array('nameFirst' => 'name',
'nameLast' => 'name',
'phone' => 'phone',
'email' => 'email');
foreach($input as $key => $value) {
switch($fieldTypes[$key]) {
case 'name':
//run $value against name validation
break;
case 'phone':
//run $value against phone validation
break;
case 'email':
//run $value against email validation
break;
default:
//code here for unknown type
}
}
Now, that could be used in any number of ways, and easily expanded to include things like if the field is required or not, or even error messages. By turning the $fieldTypes array into a multidimensional array, or an array of objects containing the data.
This way, if you decide to add a field, it would probably not involve much change in the validation code.
How about something like
<?php
$arrayFilled = true;
foreach($array as $key=>$value) {
$arrayFilled = trim($value) == '' ? false : $arrayFilled;
if($arrayFilled === false) { break; }
}
if($arrayFilled === false) {
echo "missing data";
}
else {
echo "filled array";
}
you may want to check for more than just an empty string but I'll leave that to you