i want to build a validation function(or even class) in php to check for empty fields in a form.
The thing is that i want to check the fields one after another and if there is an empty one to send "The -field_name- is empty."
If none is empty to continue with the rest of the script...
I have already made it using multiple nested if-else statements....but i was wondering if there is a more compact and programmer friendly way.
I've tried using an array which i pass in a foreach statement and then i use a switch loop.
The nested if-else's:
function no_empties($first_name,$last_name,$username,$password,$password2,$user_email,$user_email2)
{
if ( !empty($first_name) )
{ if ( !empty($last_name ) )
{if ( !empty($username ) )
{if ( !empty($password ) )
{if ( !empty($password2) )
{if ( !empty($user_email) )
{if (!empty($user_email2) )
{return TRUE;}
else{ js_msg("Please retype your email!");return FALSE;};
}
else {js_msg("Please enter a -valid- email!"); return FALSE;};
}
else{js_msg("Please retype your password!");return FALSE;};
}
else {js_msg("Please enter a password!" ); return FALSE;};
}
else {js_msg("Pleas enter a username!"); return FALSE;};
}
else { js_msg("Please enter your last name!"); return FALSE;};
}
else { js_msg("Please enter your first name!"); return FALSE;};
}
The second case i described is this:
$fields_array = array("first name"=>$first_name,"last name"=>$last_name,"username"=>$username,"password"=>$password,"retype password"=>$password2,"email"=>$user_email,"retype email"=>$user_email2);
function TEST($fields_array)
{
foreach ($fields_array as $field_name => $input)
{
switch (empty($input)) :
case TRUE: return $output="The -{$field_name}- field is empty "; break;
case FALSE:return $output= "No field is empty!!! Hooray! "; break;
endswitch;
}
}
It is working but i cannot use it like this:
if ( TEST($fields_array)==TRUE ): echo $output; else: echo $output; endif;
Moreover it would be perfect if the code was in a form that was irrelevant of how many fields each form has. Someone would just enter an array like
$fields = array ("first"=>$first,etc....) .
Any thoughts???????
I usually do it this way, find it cleaner and allows you to chain more errors at once than a single one:
$errors = array();
if(!isset($_POST['field1']) || !is_numeric($_POST['field1']) || $_POST['field1'] < 123){ $errors[] = 'Field1 is missing or has an invalid value'; }
if(!isset($_POST['field2']) || !is_string($_POST['field2']) || strlen($_POST['field2']) < 20){ $errors[] = 'Field2 is missing or is not long enough'; }
if(!isset($_POST['field3']) || !in_array($_POST['field3'], array('valid', 'values'))){ $errors[] = 'Field3 is missing or has an invalid value value not in list of (....)'; }
if(!isset($_POST['field4']) || strtotime($_POST['field4']) == false){ $errors[] = 'Field4 is missing or has an invalid date value'; }
if(count($errors) == 0){
//Process
}
Related
Here I am having 5 fields:
clgID
empID
startDate
limit
papercode
Here all fields are mandatory, suppose any one of the field is empty means I have to return like clgID should not be empty OR empID should not be empty, as per my knowledge I written the code I had posted here, but I think my logic is not correct. I hope we have to do combination logic but I don't know how to write this logic in PHP. Please any one update my code
My code:
//Test Case : 1
$case1['testCase'] = 'Checking empty condition for all fields';
$case1['clgID'] = '';
$case1['empID'] = '';
$case1['startDate'] = '';
$case1['limit'] = '';
$case1['papercode'] = '';
foreach($mainArray as $key => $val){
$input['clgID'] = $val['clgID'];
$input['empID'] = $val['empID'];
$input['startDate'] = $val['startDate'];
$input['limit'] = $val['limit'];
$input['papercode'] = $val['papercode'];
// $response = GetResponse($API_URL.'resultTrail', $input);
if($val['clgID'] != '' && $val['empID'] != '' && $val['startDate'] != '' && $val['limit'] != '' && $val['papercode'] != '' )
{
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] = 'c001';
$result[$key]['devTeamResult'] = 'success';
$result[$key]['testingTeamResult'] ='test case success';
}else
{
if($val['clgID'] == '' && $val['empID'] == '' && $val['startDate'] == '' && $val['limit'] == '' && $val['papercode'] == '' ){ // Checking empty condition for all fields
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] ='458';
$result[$key]['devTeamResult'] = 'Parameter not matching min requirement';
$result[$key]['testingTeamResult'] ='test case failure';
$result[$key]['data'] = 'All fields mandatory';
}else{
if($val['clgID'] == '' ){ // Checking empty condition for clgID
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] ='458';
$result[$key]['devTeamResult'] = 'Parameter not matching min requirement';
$result[$key]['testingTeamResult'] ='test case success';
$result[$key]['data'] ='clgID should not be empty';
}else{
if($val['empID'] == '' ){ // Checking empty condition for empID
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] ='458';
$result[$key]['devTeamResult'] = 'Parameter not matching min requirement';
$result[$key]['testingTeamResult'] ='test case success';
$result[$key]['data'] = 'empID should not be empty';
}else{
if($val['startDate'] == '' ){ // Checking empty condition for startDate
$result[$key]['testCase'] = $val['testCase'];
$result[$key]['resultCode'] ='458';
$result[$key]['devTeamResult'] = 'Parameter not matching min requirement';
$result[$key]['testingTeamResult'] ='test case success';
$result[$key]['data'] = 'startDate should not be empty';
}
}
}
}
}
}
print_r($result);
Do you really want to be writing out that much code? What happens if you have to add another mandatory field?
Instead, be more generic.
$requiredFields = ["groupID", "studentID", "startFrom", "limit", "worksheetID"];
foreach($requiredFields as $key) {
if( empty($input[$key])) {
return $key." is required"; // or whatever error message
}
}
// if you get this far, ie. without hitting the "return", then all inputs are present.
// process the data now.
You can use this pattern for each input field:
$var = isset($_POST['field']) ? $_POST['field'] : '';
// Trim any trailing whitespaces
$conditionsOk = true;
if(trim($var) === '')
{
// Empty input
$conditionsOk = false;
}
if($conditionsOk) { // Perform action: db update, email... }
Let's take this opportunity to firstly, fix the issue to check if it's empty.
In php the isset() function checks if the index is in the array, and if it's empty.
Secondly, let's go over the code and clean it up a bit; please review the changes; clean code is the most important factor in being a successful developer.
else {
if (condition) {
}
}
Re-written to:
else if (condition) {
}
That's one of the issues with the code, the second issue is the cleanliness of the code; always try to keep the nested if statements to a minimum and move functionality to functions to keep the code readable and clean. - code that is not readable or maintainable doesn't carry any value.
I would go for a mapping and use a dynamic function.
Example mapping:
$fieldsMapping = [
"field" => exampleValidationFunction(),
"field2" => ["required" => True],
]
In return you can have flexibility and easily maintain the code albeit the learning curve.
The function to go over the mapping can be as follows:
function runTestCases() {
foreach ($fieldsMapping as $field => $validationRules) {
// your code here - check if its a function.. call function.. etc..
}
}
I have a form with 25+ fields. I want to display a message if ANY of the fields in the array are NOT empty.
$customfields = array('q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10', 'q11', 'q12', 'q13', 'q14', 'q15', 'q16', 'q17', 'q18', 'q19', 'q20', 'q21', 'q22', 'q23', 'q24');
I've taken a look at similar SO questions for verifying that all fields are not empty, i.e.:
$error = false;
foreach($customfields as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "Here's an awesome message!";
} else {
echo "None for you, Glen Coco.";
}
How do I do the opposite - display a message if ANY one or more than one fields in the array are not empty?
Thanks in advance!
I think you want to take a look into the NOT operator.
You can just write this:
if (!empty($_POST[$field])) {
//^ See here the NOT operator
$error = true;
}
For more information see the manual: http://php.net/manual/en/language.operators.logical.php
Do the opposite comparison in the if:
$error = false;
foreach($customfields as $field) {
if (!empty($_POST[$field])) {
$error = true;
break; // get out of foreach loop
}
}
I have the following php code.
Im trying to find out the field name/key that does not exist without using hardcoded static text. Is there a php function that can do this. array_keys_exist is similar to what I want but it only allows for checking of a single key.
ex:
Something like
$keys_to_confirm = ['password','password_old',....];
$user_submitted_input_array = ['password'=>'...', 'somekey'=>'...' ];
bool : all_array_keys_exist($keys_to_confirm,$user_submitted_input_array);
Current code that uses static text to report the missing field/key name
if( isset($input['password']))
{
if( isset($input['password_old'])) )
{
if(isset($input['password_repeat'])) )
{
//good to go!
}
else
{
die('missing form element password_repeat.');
}
}
else
{
die('missing form element password_old.');
}
}
else
{
die('missing form element password.');
}
I had this code but it doesnt say what is missing.
//if the field doesnt exist for some reason lets create a dummy
if( ! isset($input['password'])
OR (!isset($input['password_repeat']))
OR (!isset($input['password_old'])) )
{
die('missing form element.');
}
Try:
foreach( array('password', 'password_repeat', 'password_old') as $key ) {
if( empty($input[ $key ]) ) {
echo 'Missing field: ' . $key;
}
}
You can probably come up with a one liner to do this using array_diff_key, but I think the above is concise enough.
Here's the one liner with array_key_diff. It's not the prettiest but functional.
$keys_to_confirm = array('password' => '','password_old' => '');
$user_submitted_input_array = array('password'=>'...', 'somekey'=>'...');
$validate = array_diff_key($keys_to_confirm, $user_submitted_input_array);
if( empty($validate) ) {
echo 'Passed';
} else {
echo 'Missing field: ' . key($validate);
}
My solution:
if ($field_miss = array_diff_key(array('password', 'password_old', '...'), array_keys($input))) {
echo 'Missing field: ', implode(', ', $field_miss);
}
I'm trying to validate my username as an email address, however PHP isn't letting me do this! what's wrong here?
//This checks if all the fields are filled or not
if (!empty($_POST['username']) ||
!empty($_POST['password']) ||
!empty($_POST['repassword']) ||
!empty($_POST['user_firstname']) ||
!empty($_POST['user_lastname']) ){
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
here is the form i used in register.php
<form action="createuser.php" method="post" name="registration_form" id="registration_form">
<label>Email</label>
<input name="username" type="text" id="username" size="50" maxlength="50" /><br />
Typo?
header('Location: register.php?msg=You didn't complete all of the required fields');
^---unescaped embedded quote
Your empty logic is also faulty. You're checking if any fields are NOT empty (e.g. filled out) and then complaining that they're not filled out. remove the ! to invert the logic.
if (empty(...) || empty(...) || etc...)
instead of this use regular expression for validating your email address
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!preg_match("^[^#]{1,64}#[^#]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!preg_match("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
and then check if it return true redirect it to location if not then simply throw an error
You would not get to Validate the email because your if statement is wrong .. it is checking if any of the post is not empty.
Replace it with
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])) {
For starters, look at the syntax highlighting for why you're getting parse errors.
header('Location: register.php?msg=You didn't complete all of the required fields');
needs to become:
header('Location: register.php?msg=You didn\'t complete all of the required fields');
How about you use javascript window.location? Sometimes header function is sensitive.And also put a submit button in your form since by default fields are empty when loaded.
if(isset($_POST['your_submit_button_name'])){
if (empty($_POST['username']) ||
empty($_POST['password']) ||
empty($_POST['repassword']) ||
empty($_POST['user_firstname']) ||
empty($_POST['user_lastname']) ){
?>
<script>
window.location = 'register.php?msg=You didn\'t complete all of the required fields';
</script>
<?php
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
}
NOTE: I remove "!" before your empty function since youre trapping the fields that are empty.
Try to use this solution:
$FormData = $_POST;
if(isset($FormData['button_name'])){
$Errors = array();
foreach ($$FormData as $key => $value) {
if(empty($value)) $Errors[] = 'Some message';
if($key = 'username'){
if(filter_var($value, FILTER_VALIDATE_EMAIL){
$Errors[] = 'The email address you entered is not valid';
}
}
}
if(empty($Errors)){
// #todo Do some action
} else {
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
}
function check_email($check) {
$expression = "/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/";
if (preg_match($expression, $check)) {
return true;
} else {
return false;
}
}
Now use this method as :
if(!check_email($_REQUEST['ContactEmail'])){
$register_error .="Enter the correct email address!<br />";
$reg_error=1;
}
I've a form,in the form only few fields are mandatory.When a fields is not mandatory,it should not check for empty data validation.If the non mandatory field contain data then it shoudl check the data,validation should happen only when data present.
My below code check for all fields.For eg:Say phone is not mandatory in below code,how to change the code.
$validate = array(
array($x, '/^[a-z\d ]{4,20}$/i', "Please enter valid name."),
array($y, '/^[a-z\d ]{4,20}$/i', "Please enter a real category."),
array($phone, '/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/' , "Please enter a valid phone number")
);
$error = '';
foreach ($validate as $validation)
{
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
if($error != '')
{
echo $error;
exit;
}
Comment on this post,if it is not clear.
Thanks in advance!
If you want to check if at least required fields have been submitted, you can check whether they have been set and have a truthy value using the isset and empty functions.
For example:
if ( isset($_POST['username'], $_POST['password']) &&
! empty($_POST['username']) && ! empty($_POST['password']) ) {
// validation here
}
That would check if the username and password fields were submitted and have a value, whereas for example an email field wouldn't necessarily have been filled in for the above condition to return true.
If you know the mandatory fields before hand I'll suggest you group them in an array and test for based on the current key. If a key is in not mandatory but holds value you can test otherwise do your regular check.
$error = '';
$mandatoryFields = array('key1', 'key2' 'key3');
foreach ($validate as $validation)
{
if (!in_array($validation[0], $mandatoryFields) && strlen(trim($validation[0])) > 0)
{
// There is data in a non mandatory field.
// Perform your test.
}
else {
// Do your regular test.
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
}
You can give this a try.