Can I display a single message for the multiple form fields in CodeIgniter?
For example, I have set following rules for the email and password fields. I want to display only one message if any of these two fields is invalid. (eg. invalid email or password ")
$this->form_validation->set_rules('email_address', 'Email Address', 'valid_email|required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');
How i can do that? Thanks for any help.
Edit: Sorry if my question is not clear. Currently I'm using validation_errors(), and i get errors of each field. However, I want to show a same error message if any of the two fields (email or password) is invalid. No matter if email is invalid, or if password is invalid, or both are invalid, it should print a single message, such as: invalid email or password.
I'm not sure if this is what you need, but you can try:
if($this->form_validation->run() == FALSE){
$message = 'Your error message here'; //validation_errors() works too.
}else{
$message = 'Your success message here';
}
$this->load->view('yourview',array('feedback_message'=>$message));
If you don't care which field isn't valid, then this snippet is ok. "Something is wrong, i don't care what's wrong, tell the user".
Iterate over each field and check using form_error(), add any invalid field names to a single error string:
if($this->form_validation->run() == FALSE){
$fields = array('email_address', 'password');
$invalid_fields = array(); //where we'll store invalid field names
foreach($fields as $field){
if(form_error($field)){
$invalid_fields[] = $field;
}
}
$data['error_message'] = 'The following fields are invalid: ' . implode(",", $invalid_fields);
}
$this->load->view('yourview', $data); //if !empty($error_message) in view echo it out
In your view you can just do this:
<?php if(!empty($this->form_validation->_error_array)): ?>
<p>There were some errors.</p>
<?php endif; ?>
$this->form_validation->set_message('rule', 'Error Message');
I think ,setting the same error message for both the rules will do the job ;)
Related
I have to do the following for a large amount of session variables, is there a way I can shorten this code to apply to all the variables rather than repeatedly writing out if(!isset($_SESSION['whatever'])) and adding the apropriate error to the errors array.
if(!isset($_SESSION['fiat'])) {
$errors[fiat] = 'Please enter valid amount';
}
if(!isset($_SESSION['contact'])) {
$errors[contact] = 'Please enter valid contact';
}
if(!isset($_SESSION['name'])) {
$errors[name] = 'Please enter valid name';
}
I have tried some things with for loops and arrays but am really struggling even after some serious googling, so any help much appreciated.
Thanks!
I have now made the following array but am unsure how to use it:
$errors = array(
$_SESSION['fiat'] => 'Please enter valid amount',
$_SESSION['contact'] => 'Please enter valid contact',
$_SESSION['name'] => 'Please enter valid name',
);
Do i do something like the following? Not sure what goes inbetween.
for(!isset($errors)){
}
What you can do is the following:
$errors = array();
// List all session parameters and error messages you want to check here
$valuesToCheck = array(
'fiat' => 'Please enter valid amount',
'contact' => 'Please enter valid contact'
// and so on...
);
// Loop through all values you want to check and validate it. if validation doesn't pass add error message to $errors array.
foreach ($valuesToCheck as $k => $v) {
if(!isset($_SESSION[$k])) {
$errors[$k] = $v;
}
}
// Check if after the validation array with errors is not empty then deal with it.
if (!empty($errors)) {
// Do something with errors here
}
PS: I think you should learn more about software development basics before start writing a code. This will be useful in your further career.
I am adding a contact page to my website, but having issues with the comment text box. When the user enters invalid information into the name and email text field, the website redirects the user back to the contact page to fill out the correct information. However, I want the comment box to be optional for the user. For example, the user will enter their name and email, but doesn't have any comments. The code should then process the information. Currently, my code will redirect the user back to the contact page because the user did not enter any information into the comment box. Any suggestions on how to fix this error?
Thanks!
if (empty($_REQUEST['comment'])) {
$error = TRUE;
} else {
$comment = $_REQUEST['comment'];
$form['comment'] = $comment;
if (!preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}
}
If you want to allow the content box to be empty, just let an empty value be an acceptable value. This means only running your validation against that field if there is a value present. This means removing your if/else statement since empty($_REQUEST['comment']) is no longer a valid check.
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
I just added !empty($comment) && to your check which basically says, "if there is a value go ahead and validate it".
One thing you should also do if you use this code is trim whitespace from your comment box values. Otherwise a user could type a space character and that would not be considered empty:
$comment = trim($_REQUEST['comment']);
Final code:
$comment = trim($_REQUEST['comment']);
$form['comment'] = $comment; // I am assuming this is used elsewhere
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}
Hi :) This is my first time posting on here but I can't figure it out and it should be simple. I think I have just been looking at it for too long. So I have a form for which I am carrying out form validation, all the validation works and it sends to the database.
The small issue I have is when it comes to the email and confirm email validation, the first if statement checks if the textbox is empty and if it is I should get the "Email is required" message. But due to the second if statement, I think the $emailErr variable gets overwritten by the second error message which should appear only if the email syntax is invalid.
Therefore, if i leave the textbox empty, i still get the "syntax invalid" message rather than the "email is required" message.
My confusion comes from the fact that, for example, my "firstname" validation (and all other validation) is pretty much the same idea but they do not get overwritten by the second error message which is also presented by using a second if statement.
I will copy the code for my firstname validation and the code for my email validation so you can get an idea of what I am talking about. Any help would be greatly appreciated. If not, im sure ill figure it out eventually :) Thanks!
FIRST NAME VALIDATION - if I leave the textbox blank I get error message "First name is required" - which is correct.
//Check if the firstname textbox is empty
if (empty($_POST['fname']))
//Show error message
{
$fnameErr = "First name is required";
}
//Check if fname is set
elseif (isset($_POST['fname']))
//Check the text using the test_input function and assign it to $fname
{$fname = test_input($_POST['fname']);}
//Check if first name contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname))
//Show error message & unset the fname variable
{
$fnameErr = "Only letters and white space allowed";
unset($_POST['fname']);
}
else
//Check the text using the test_input function and assign it to $fname
{$fname = test_input($_POST['fname']);}
EMAIL VALIDATION - if I leave the textbox empty I get the error message "Invalid Email Format" - it should be "Email is required" - why is this?
//Check if the email textbox is empty
if (empty($_POST['email']))
//Show error message
{
$emailErr = "Email is required";
}
//Check if email is set
elseif (isset($_POST['email']))
//Check the text using the test_input function and assign it to $email
{$email = test_input($_POST['email']);}
//Check if e-mail syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
//Show error message & unset the email variable
{
$emailErr = "Invalid email format";
unset($_POST['email']);
}
else
//Check the text using the test_input function
{$email = test_input($_POST['email']);}
The proper way to validate an email is by using filter_var
$email = filter_var(filter_var($_POST['email'],FILTER_SANITIZE_EMAIL),FILTER_VALIDATE_EMAIL)
if(!$email)
$invalidemailMessage = 'You have entered an invalid email address!';
End of story.
If you really,really,really need to output "Email required":
if($_POST['email'] == "" || preg_match('/^\s+$/', $_POST['email']) == true) {
$invalidemailMessage = 'Email required.';
} else {
$email = filter_var(filter_var($_POST['email'],FILTER_SANITIZE_EMAIL),FILTER_VALIDATE_EMAIL)
if(!$email)
$invalidemailMessage = 'You have entered an invalid email address!';
}
with some adjustment to your current code you can keep it, ALTHOUGH what #tftd said is absolutely correct with regard to Sanitisation and Validation.
$error = array();
if (empty($_POST['email'])) {
$error[__LINE__] = "Email is required";
} elseif (isset($_POST['email'])) {
$email = test_input($_POST['email']);
}
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$error[__LINE__] = "Invalid email format";
unset($_POST['email']);
} else {
$email = test_input($_POST['email']);
}
if ($error){
print_r($error);
}
Part of your problem with your code is your last if is still being ran so you will always get the error if the email field is empty.
Change this
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
To this
if (isset($email) && !preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
I can't find a damned bit of documentation for using the Constant Contact REST API to check if an email address is in a list or not.
The following seems to be completely useless:
include_once('cc_class.php');
$ccContactOBJ = new CC_Contact("basic", $cckey, $ccuser, $ccpass);
if(($_SERVER['REQUEST_METHOD']=="POST") && !empty($_REQUEST['member-submit'])) {
$contact = $ccContactOBJ->getSubscribers(urlencode($_POST['MemberEmail']));
if (empty($contact['items'])) {
$message = 'You are not listed in our database.';
}
else {
$message = 'You are already listed in our database';
}
echo $message;
}
Anyone have ANY idea how to return a true or false value?
Here's what I'm trying to do:
$errmsg_1 = 'Please make changes to your post';
$errmsg_2 = 'Please make changes to your post image';
$error = 1;
echo $errmsg_.$error; //'Please make changes to your post';
Nothing will work, and there are many error messages like these ones that I have to echo.
Can anyone help?
What you're asking for is known as a variable variable -- see http://uk.php.net/manual/en/language.variables.variable.php for more info.
But please don't do that; it's considered very poor coding practice.
What you actually need is an array:
$errmsg = array(
'Please make changes to your post', //this will be $errmsg[0]
'Please make changes to your post image' //this will be $errmsg[1]
);
$error = 0; //nb: arrays start at item number 0, not 1.
echo $errmsg[$error];
That's much better coding practice than messing around with variable variables.
Store error messages in array:
$errmsg[1] = 'Please make changes to your post';
$errmsg[2] = 'Please make changes to your post image';
// and so on
$error = 1;
echo $errmsg[$error];
Try
echo {'$errmsg_' . $error};
Although you're doing this really rather incorrectly. You should be using an array instead; concatenating variable names is bad practice and leads to messy/unreadable/broken code. Using an array would work like this:
$errors = array(
'Please make changes to your post',
'Please make changes to your post image'
);
echo $errors[$error];
Although bear in mind that $error starts from 0 as arrays are 0-index based.
Off the top of my head I think you want $errmsg_{$error}, but I'm not in a position to test/double check that right now.
This should work:
$errmsg_1 = 'Please make changes to your post';
$errmsg_2 = 'Please make changes to your post image';
$error = 1;
echo ${'errmsg_ ' . $error};
No offence meant but what you're doing is bad design.
A small but no means perfect solution would be store your errors as an Array.
$errors = array('Please make changes to your post', 'Please make changes to your post image');
$error = 0;
echo $errors[$error];
Try using this ${$errmsg_.$error}
This is a variable variable: http://php.net/manual/en/language.variables.variable.php
You're trying to do this:
function errorMsg($code)
{
$msg;
switch($code)
{
case 1:
$msg = 'Please make changes to your post';
break;
case 2:
$msg = 'Please make changes to your post image';
break;
}
return $msg;
}
echo errorMsg(1);
$error_msg = 'Please make changes to your ';
$error[1] = 'post';
$error[2] = 'post image';
for($i=1; $i<=count($error); $i++)
echo $error_msg . $error[$i];
Use arrays. keep the indexes for easy future reference, as well as easy error message changing and organized API.
$errmsg = array(
1 => 'Please make changes to your post',
2 => 'Please make changes to your post image'
);
$error = 1;
echo $errmsg[$error]; //'Please make changes to your post';