How to display error message properly from check_required_fields function? - php

Hi i'd like some help please. i'm having a function for validating required fields of forms, in which i pass the req. fields in an array, so if is empty e.g first_name returns an error message: "The first_name is empty." . The problem is that i would like to make the name of the field in the message to look more "friendly" to the user, no camelCases or '_'. How can i achieve this?
p.s. here's my code:
$required_fields = array('first_name', 'last_name', 'email', 'profileInfo', 'message');
$errors = array_merge($errors, check_required_fields($required_fields));
Right now the output error message looks like :
"The first_name is required" or "The profileInfo is required".
The function is this:
function check_required_fields($required_fields) {
$field_errors = array();
foreach($_POST as $field=>$value){
if(empty($value) && in_array($field, $required_fields) === true){
$field_errors[] = "the " . $field . " is required.";
//break 1;
}
}
return $field_errors;
}

You could give each required field a label...
$required_fields = array(
'first_name' => 'First Name',
'last_name' => 'Last name',
'email' => 'Email Address',
'profileInfo' => 'Profile information',
'message' => 'Message'
);
$errors = array_merge($errors, check_required_fields($required_fields));
You will need to alter check_required_fields method to handle the $required_fields array correctly, like this:
function check_required_fields($required_fields)
{
$field_errors = array();
foreach ($_POST as $field => $value)
{
if (empty($value) && array_key_exists($field, $required_fields) === true)
{
$field_errors[] = "the " . $required_fields[$field] . " is required.";
//break 1;
}
}
return $field_errors;
}
Edit: I have just noticed that your loop on $_POST will only work as expected if the fields are set. Try the following:
function check_required_fields($required_fields)
{
$field_errors = array();
foreach ($required_fields as $field => $label)
{
$value = $_POST[$field];
if (empty($value))
{
$field_errors[] = "the " . $label . " is required.";
//break 1;
}
}
return $field_errors;
}

Related

how to update looping form in codeigniter 3?

i have a problem where i want to update a looping form in codeigniter 3. in column nik_pindah where have a id_surat is same
---MY CONTROLLER WITH FORM VALIDATION---
public function update_nik_pindah_kelurahan($id_surat_pindah){
$this->load->library('form_validation');
$i = 0; // untuk loopingnya
$a = $this->input->post('nik_pindah');
if ($a[0] !== null){
foreach ($a as $row => $val){
$this->form_validation->set_rules("nik_pindah[$i]","nik_pindah", "integer|callback_nik_pindah_available");
}
}
$this->form_validation->set_message('required', 'Mohon isi %s terlebih dahulu');
$this->form_validation->set_message('integer', 'Isi %s hanya menggunakan angka');
if ($this->form_validation->run() == FALSE){
$this->edit_nik_pindah_kelurahan($id_surat_pindah);
} else {
$id_surat_pindah = $this->input->post('id_surat_pindah');
$id_surat = $this->input->post('id_surat');
$i = 0; // untuk loopingnya
$a = $this->input->post('nik_pindah');
if ($a[0] !== null) {
$data = array(
'id_surat' => $id_surat,
'id_surat_pindah' => $id_surat_pindah
);
foreach ($a as $row) {
$dataaa = [
'id_surat' => $id_surat_pindah,
'nik_pindah' =>$row,
];
$wheree = array(
'id_surat' => $id_surat_pindah
);
$this->db->where('id_surat', $id_surat_pindah);
$update = $this->db->update('nik_pindah', $dataaa);
if ($update) {
$i++;
}
}
$where = array(
'id_surat_pindah' => $id_surat_pindah
);
$this->m_pindah_kelurahan->update_data($where, $data, 'surat_pindah');
}
redirect('admin_pindah_kelurahan/index');
}
}
---MY CONTROLLER WITHOUT FORM VALIDATION---
public function update_nik_pindah_kelurahan($id_surat_pindah){
if ($this->form_validation->run() == FALSE){
$id_surat_pindah = $this->input->post('id_surat_pindah');
$id_surat = $this->input->post('id_surat');
$i = 0; // untuk loopingnya
$a = $this->input->post('nik_pindah');
if ($a[0] !== null) {
$data = array(
'id_surat' => $id_surat,
'id_surat_pindah' => $id_surat_pindah
);
foreach ($a as $row){
$dataaa = [
'id_surat' => $id_surat_pindah,
'nik_pindah' =>$row,
];
$wheree = array(
'id_surat' => $id_surat_pindah
);
$this->db->where('id_surat', $id_surat_pindah);
$update = $this->db->update('nik_pindah', $dataaa);
if ($update) {
$i++;
}
}
$where = array(
'id_surat_pindah' => $id_surat_pindah
);
$this->m_pindah_kelurahan->update_data($where, $data, 'surat_pindah');
}
redirect('admin_pindah_kelurahan/index');
}
}
---MY VIEWS---
<?php
foreach ($nik_pindah_kelurahan as $np) :
if (empty($np->nik_pindah)) { ?>
<input type="text" name="nik_pindah" class="form-control" value="belum tersedia"><br>
<?php } else {?>
<input type="text" name="nik_pindah[]" class="form-control" value="<?php echo $np->nik_pindah ?>"><br>
<?php } endforeach; ?>
If with or without form validation will updating data but all column where id_surat is same (not particular value)
like this:
enter image description here then enter image description here
Everytime the foreach makes a loop, $this->db->where() has the same condition because $id_surat_pindah has always the same value, so you're updating the same rows once and once again. Also (if I understand it correctly), keep in mind that if $id_surat_pindah is not a unique key, everytime you make an UPDATE all the rows with its value will be affected.
Otherwise, I would recommend you to check your code using update_batch() instead the loop: https://www.codeigniter.com/userguide3/database/query_builder.html?highlight=update_batch

PHP function errors not showing

I wasn't entirely sure how to search for this question, so if it has been asked before please send me in the right direction.
I have a validation function with an array. Inside my array I have set up errors to be displayed if one of the form fields doesn't validate. If the user fills a field out wrong, they should get an error of which field was wrong and the form should be still present. However, they get a blank page with only the generic error (the one I echo when I called the function) and not the field-specific error. Can someone please tell me where I went wrong?
$output_form = 1; //control if form displays - yes
$error_text = '';
//declare form elements (empty first load)
$fname = '';
$valid_fname = 0;
$fname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$fname_error_message = 'First name must be 2-15 alphabetic characters only.<br>';
$lname = '';
$valid_lname = 0;
$lname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$lname_error_message = 'Last name must be 2-15 alphabetic characters only.<br>';
$phone = '';
$valid_phone = 0;
$phone_regex = '/^\(\d{3}\)\d{3}-\d{4}$/';
$phone_error_message = 'Phone number must be in (xxx)xxx-xxxx format.<br>';
$city = '';
$valid_city = 0;
$city_regex = '/^([A-Z]|[a-z]){2,15}$/';
$city_error_message = 'City must be 2-15 alphabetic characters only.<br>';
$state = '';
$valid_state = 0;
$state_regex = '/^([A-Z]|[a-z]){2}$/';
$state_error_message = 'State must be 2 alphabetic characters only.<br>';
//data posted
if (isset($_POST['submit'])) {
if ($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
}//end debug
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$phone = trim($_POST['phone']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$phone_replace = preg_replace('/[\(\)\-\s]/', '', $phone);
function validate_form($fields, &$errors = []) {
$errors = [];
foreach ($fields as $name => $field) {
if (!preg_match ($field['regex'], $field['value'])) {
$errors[$name] = $field['error'];
$output_form = 1;
}
}
return empty($errors); //returns true/false
}
$fields = [
'fname' => ['regex' => $fname_regex, 'value' => $fname, 'error' => $fname_error_message],
'lname' => ['regex' => $lname_regex, 'value' => $lname, 'error' => $lname_error_message],
'phone' => ['regex' => $phone_regex, 'value' => $phone, 'error' => $fname_error_message],
'city' => ['regex' => $city_regex, 'value' => $city, 'error' => $city_error_message],
'state' => ['regex' => $state_regex, 'value' => $state, 'error' => $state_error_message],
];
$errors = [];
if (!validate_form($fields, $errors)) {
echo "<p>One of your fields is invalid. Please check and re-submit.</p>";
$output_form = 1;
return (false);
}
else {
$output_form = 0;
}
foreach($errors as $error) echo "<p>$error</p>";
Actually outputting stuff usually helps ;)

Header location - This webpage has a redirect loop

Hi I am trying to redirect to a form page however I got the following message
ERR_TOO_MANY_REDIRECTS
I have been able to figure that
header('Location: http://localhost:8888/wordpress/send');
is causing the error I have tried a number of different things including adding exit underneath the final line of code but it still seems to be looping.
<?php
/*
Template Name: Send
*/
?>
<?php
session_start();
require_once(get_template_directory().'/vendor/PHPMailer/PHPMailerAutoload.php');
$errors = [];
if(isset($_POST['customername'], $_POST['email'], $_POST['message'])) {
$fields = [
'name' => $_POST['customername'],
'email' => $_POST['email'],
'message' => $_POST['message']
];
foreach ($fields as $field => $data) {
if (empty($data)) {
$errors[] = 'The ' . $field . ' field is required';
}
}
} else {
$errors[] = 'Something went wrong.';
}
header('Location: http://localhost:8888/wordpress/send');
exit();

Laravel validator 'in' issue for numbers in input

I need help in fixing an issue in which I am using laravel 'in' validator to match a given input against multiple comma separated string of values. Now the issue is when there is a number in the input and it does not matches with any of the comma separated values then it gives an exception:
preg_match() expects parameter 2 to be string, array given
However it should simply give error message in validator object that input field does not match. instead it gives above mentioned exception. Following is my code:
if (!empty($program)) {
$institution_id = $program->InstitutionId;
$roster_users = $program->usersRosters()->where('ProfileType', 'Student')->get();
if (!empty($roster_users)) {
$rostered_users_ids = implode(',', $roster_users->lists('id'));
}
if (!empty($roster_users)) {
$rostered_users_usernames = implode(',', $roster_users->lists('UserName'));
}
$teacher_roster_users = $program->usersRosters()->where('ProfileType', 'External Staff')->get();
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_usernames = implode(',', $teacher_roster_users->lists('UserName'));
}
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_data = $teacher_roster_users->lists('id', 'UserName');
}
}
$rules = [
'aasectionname.required' => '501 – AA section does not exist',
'aaid' => 'numeric|exists:users,id|in:' . $rostered_users_ids . '|aaidinstitutionmismatch:' . $institution_id,
'institutionid' => 'numeric|in:' . $institution_id,
'username' => 'exists:users,UserName|in:' . $rostered_users_usernames . '|usernameinstitutionmismatch:' . $institution_id,
'schoolid' => 'numeric',
'groupowner' => 'in:'.$teacher_rostered_users_usernames,
'remove' => 'in:0,1'
];
$messages = [
// InstitutionId
'institutionid.numeric' => '101 – Invalid Institution ID',
'institutionid.in' => '102 – Institution ID does not match Program',
// Usernames
'username.exists' => '201 – UserName does not exist',
'username.in' => '202 – UserName is not rostered to this program',
'username.usernameinstitutionmismatch' => '203 – User/Institution Mismatch - UserName is not assigned to this Institution',
// AAId
'aaid.numeric' => '301 – AA ID does not exist',
'aaid.exists' => '301 – AA ID does not exist',
'aaid.in' => '302 – AA ID is not rostered to this program',
'aaid.aaidinstitutionmismatch' => '303 – AA ID/Institution Mismatch – AAID is not assigned to this Institution',
// Mismatch
'bothmismatch' => '401 – AAID/UserName/SchoolID do not match (This is a combination of at least 2 of these items)',
// Teacher
'groupowner.in' => '501 – GroupOwner does not exist',
// Remove
'remove' => '601 – No Student record match to remove',
];
Excel::load($file, function($excel) use($program, $rules, $messages, $errors, &$errors_data, $teacher_rostered_users_data) {
global $totalmismatch;
$results = $excel->get();
$program_group_model = new ProgramGroup;
$option_model = new Option;
$group_default_status_id = key($option_model->getProgramsStatus(['Active']));
$groupVisibilityStatusId = $group_type = $option_model->getVisibilityOptions('Question Visibility','Private');
$data = [];
$lastSecId = null;
$groupSectionPreviousName = null;
$groupname = null;
$data['status'] = $group_default_status_id;
$data['program_id'] = $program->Id;
$groupname_lists = $program_group_model->with(['programs' => function ($query) use ($program){
$query->where('ProgramId','=',$program->Id);
}])->get()->lists('Name','Id');
foreach ($results as $key => $row) {
$inputs = $row->toArray();
$groupname = trim($inputs['usergroup']);
$errors = [];
// Stop reading the excel when aasectionname is empty
if (empty($groupname) || $groupname == null) {
$errors['remove'] = $messages['aasectionname.required'];
}
$validator = Validator::make($inputs, $rules, $messages);
if ($validator->fails()) {
$errors = $validator->messages()->toArray();
foreach ($errors as $error) {
foreach ($error as $e) {
$errors_data[] = [$key + 2, $e];
}
}
} else {
$aaid = intval($inputs['aaid']);
$groupowner_name = $inputs['groupowner'];
if (!empty($teacher_rostered_users_data[$groupowner_name])) {
$groupowner_id = $teacher_rostered_users_data[$groupowner_name];
$data['owner'] = $groupowner_id;
}
$remove = intval($inputs['remove']);
// Remove existing Student Roster
if (!empty($remove)) {
$removed = false;
$user_ids = is_array($aaid) ? $aaid : [$aaid];
$program_group = $program->programGroups()->where('Name', $groupname);
if (!empty($program_group)) {
$program_group = $program_group->first();
}
if (!empty($program_group)) {
$program_group = $program_group->users();
}
if (!empty($program_group) && !empty($user_ids)) {
$removed = $program_group->detach($user_ids);
}
if (!$removed) {
$errors['remove'] = $messages['remove'];
}
} else {
if (!in_array($groupname, $groupname_lists) || $groupSectionPreviousName != $groupname) {
$data['name'] = $groupname;
$data['group_id'] = array_search($groupname, $groupname_lists);
$data['group_type'] = $groupVisibilityStatusId;
$sectionId = $program_group_model->saveProgramGroup($data);
$data[$sectionId]['selected'][] = $aaid;
$groupname_lists[$sectionId] = $groupname;
} else {
$temp = array_flip($groupname_lists);
$data[$temp[$groupname]]['selected'][] = $aaid;
}
}
if ($totalmismatch === 2) {
$errors['bothmismatch'] = $messages['bothmismatch'];
}
foreach ($errors as $error) {
$errors_data[] = [$key + 2, $error];
}
}
$groupSectionPreviousName = $groupname;
}
$programAASectionModelForSectionUsers = new ProgramSectionUser();
$programAASectionModelForSectionUsers->saveProgramGroupUsers($data);
});
$rules
array:7 [
"aasectionname.required" => "501 – AA section does not exist"
"aaid" => "numeric|exists:users,id|in:28,29,32,33,25,24,27|aaidinstitutionmismatch:42"
"institutionid" => "numeric|in:42"
"username" => "exists:users,UserName|in:Kabeer,Ayaz,fddesaaweqq,fdawerascvdfc,haseeb,kamran,shahid|usernameinstitutionmismatch:42"
"schoolid" => "numeric"
"groupowner" => "in:externalstaff,rahat,uzma,sahar,haseebahmad,saimariaz,fredrick"
"remove" => "in:0,1"
]

checking for mandatory parameters in an API

Im building an API which requires some mandatory parameters to be POSTed to it.There are about 15 mandatory parameters which should be passed to the api,I wanted to show relevant errors to the developer if there is any parameter missing like "Could not process ; email parameter is missing ".
I have already implemented the logic,but its not working well and seems to be very badly coded with excess codes.This is the current approach
if ($data['email'] AND array_key_exists('email', $data)) {
if (!validateEmail($data['email'])) {
$transaction_error = 'Invalid email';
}
} else {
$transaction_error = 'Parameter email is missing';
}
if (!($data['addr'] AND array_key_exists('addr', $data))) {
$transaction_error= 'Parameter addr is missing';
}
if (array_key_exists('show_shipping_addr', $data)) {
if (!verifyBinary($data['show_shipping_addr'])) {
$transaction_error = 'Invalid show_shipping_addr';
}
} else {
$transaction_error = 'Parameter show_shipping_addr is missing';
}
if (array_key_exists('authorize_user', $data)) {
if (!verifyBinary($data['authorize_user'])) {
$transaction_error = 'Invalid authorize_user';
}
} else {
$transaction_error = 'Parameter authorize_user is missing';
}
if ($data['mobileNo'] AND array_key_exists('mobileNo', $data)) {
if (!validateMobileNo($data['mobileNo'])) {
$transaction_error = 'Invalid mobileNo';
}
} else {
$transaction_error = 'Parameter mobileNo is missing';
}
if ($data['currency_code'] AND array_key_exists('currency_code', $data)) {
if (!validateCurrencyCode($data['currency_code'])) {
$transaction_error = 'Invalid currency_code';
}
} else {
$transaction_error = 'Parameter currency_code is missing';
}
if ($data['checksum_method'] AND array_key_exists('checksum_method', $data)) {
if (!validateChecksumMethod($data['checksum_method'])) {
$transaction_error = 'Invalid checksum_method';
}
} else {
$transaction_error = 'Parameter checksum_method is missing';
}
if ($data['zipcode'] AND array_key_exists('zipcode', $data)) {
if (!validateZipCode($data['zipcode'])) {
$transaction_error = 'Invalid zipcode';
}
} else {
$errors[$i++] = 'Parameter zipcode is missing';
}
if ($data['f_name'] AND array_key_exists('f_name', $data)) {
if (!validateAlphaString($data['f_name'])) {
$transaction_error = 'Invalid name';
}
} else {
$transaction_error = 'Parameter f_name is missing';
}
if ($data['state'] AND array_key_exists('state', $data)) {
if (!validateAlphaString($data['state'])) {
$transaction_error = 'Invalid state';
}
} else {
$transaction_error = 'Parameter state is missing';
}
if ($data['country'] AND array_key_exists('country', $data)) {
if (!validateAlphaString($data['country'])) {
$transaction_error = 'Invalid country';
}
} else {
$transaction_error = 'Parameter country is missing';
}
if ($data['city'] AND array_key_exists('city', $data)) {
if (!validateAlphaString($data['city'])) {
$transaction_error = 'Invalid city';
}
} else {
$transaction_error = 'Parameter city is missing';
}
/* Validation of mandatory parameters ends here */
/* Validation of optional parameters starts here
*shipping_email
*shipping_mobileNo
*shipping_zipcode
*l_name
*shipping_addr
*shipping_city
*shipping_state
*shipping_country
*surl
*furl
*rurl
*/
if (array_key_exists('l_name', $data)) {
if (!validateAlphaString($data['l_name'])) {
$transaction_error = 'Invalid l_name';
}
}
if (array_key_exists('shipping_addr', $data)) {
if (!$data['shipping_addr']) {
$transaction_error = 'Parameter shipping_addr is missing';
}
}
if (array_key_exists('shipping_mobileNo', $data)) {
if (!validateMobileNo($data['shipping_mobileNo'])) {
$transaction_error = 'Invalid shipping_mobileNo';
}
}
if (array_key_exists('shipping_city', $data)) {
if (!validateAlphaString($data['shipping_city'])) {
$transaction_error = 'Invalid shipping_city';
}
}
if (array_key_exists('shipping_state', $data)) {
if (!validateAlphaString($data['shipping_state'])) {
$transaction_error = 'Invalid shipping_state';
}
}
if (array_key_exists('shipping_country', $data)) {
if (!validateAlphaString($data['shipping_country'])) {
$transaction_error = 'Invalid shipping_country';
}
}
if (array_key_exists('shipping_zipcode', $data)) {
if (!validateZipCode($data['shipping_zipcode'])) {
$transaction_error = 'Invalid shipping_zipcode';
}
}
if(isset($api_error)) // IF there are API error pages are rendered
{
$api_error_array['api_error'] = $api_error;
$this->render_api_errors($api_error_array);
}
else if (isset($transaction_error)) { //If there are transactional errors,user is redirected back to mercahnt response url
$api_data = $this->paymentgateway->getAPIData($data['app_used'], $data['apikey']);
$data['response_url'] = $api_data['response_url'];
$data['transaction_errors'] = $transaction_error;
$this->paymentgateway->logApiRequest($data['app_used'], $transaction_error, 'Notice', $data['ip_address'], $data['ip_address_customer']);
$this->redirect_transactional_error($data);
} else {
$this->process($data); //Calls the process function when everything is done
}
I have got some set of mandatory fields and some set of non mandatory fields.The non mandatory fields if set need to be checked for their validity.
Please suggest a convienient way for validating post requests without making the code heavy.I have seen the following codes
if($_SERVER['REQUEST_METHOD'] != "POST")
die("Error: Wrong method");
$fields = array("f1", "f2", "f3", "f4");
$field_names = array("field1", "field2", "field3", "field4");
$length = count($fields);
$missing_input = array();
for($i = 0; $i < $length; $i++)
if(empty($_POST[$fields[$i]]))
$missing_input[] = $field_names[$i];
if(!empty($missing_input))
die("Error: " . implode(", ", $missing_input)");
from SO which makes sense.Can some suggest me a best practice of validating mandatory parameter in an API and showing relevant errors based on that?Instead of validating each paramters individually,can i make a single function whcih will check for the paramters and show the errors?
You can create one array of fields name which need to be mandatory / validated
$validate = array(
'username' => array('mandatory' => true, 'regex' => '/^[a-z0-9_-]{3,16}$/'),
'password' => array('mandatory' => true, 'regex' => null),
// Same like the above example you can create all validation
)
$missing_input = array();
foreach($_POST as $key => $val){
$mandatory = isset($validate[$key]) ? $validate[$key] : false;
if($mandatory && !trim($val)){
// Manage error here
$missing_input[] = $key;
}
// Same like above get the regex and validate the field here and manage the error
}
// Return / Print error array
if(!empty($missing_input))
die("Error: " . implode(", ", $missing_input)");
you can also define the min and max limit in the $validate array and inside the foreach loop validate accordingly, simple logic to validate asper your requirement.
$validate = array(
'username' => array('mandatory' => true, 'regex' => '/^[a-z0-9_-]{3,16}$/'),
'password' => array('mandatory' => true, 'regex' => null),
// Same like the above example you can create all validation
)
$missing_input = array();
$invalid_input = array();
foreach($_POST as $key => $val){
$mandatory = isset($validate[$key]['mandatory']) ? $validate[$key]['mandatory'] : false;
$regex = isset($validate[$key]['regex']) ? $validate[$key]['regex'] : null;
if($mandatory && !trim($val)){
// Manage error here
$missing_input[] = $key;
} else if($regex != null && trim($val)){
if(!preg_match($regex,$val)){
$invalid_input[] = $key;
}
}
}
// Return / Print error array
if(!empty($missing_input))
die("Missing Inputs: " . implode(", ", $missing_input). "Invalid Inputs" . implode(", ", $invalid_input));
$data = array('addr'=>'test','mobileNo'=>'test');//only for test
$dataMandatory = array('email'=>1,'addr'=>1,'mobileNo'=>1);//array of mandatory field
$transaction_error=array();//array to contain error
foreach($data as $key=>$value){
if (array_key_exists($key, $dataMandatory)) {
unset($dataMandatory[$key]);
if(!call_user_func('validate'.ucfirst($key), $value)){//i call valide method
$transaction_error[] = 'Invalid '.$key;
}
}
}
if(count($dataMandatory)!==0){
$transaction_error[] = 'Parameter missing : '.implode(',',array_flip ($dataMandatory));
}
Pros : only on array to change for add mandatory field, no duplicate code
Cons : u cant change function name (valideKey) and custom treatment

Categories