I use Codeigniter 3 and form validation. I didn't find in doc, but is there a way to add a simple value test as error ?
I have my form validation :
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('date', 'Date', 'required');
This data is from my post form, but I want to add an error from a value like :
if ($other_field != 'test') {
// how to add a custom message without callback nor fields
$this->form_validation->set_rules('no_field_here', 'Custom error', 'required');
}
Is there a kind of simple way ?
You should do like this if you want custom message for specific field :
$this->form_validation->set_rules('no_field_here', 'Custom error', 'required',array('required' => 'You must provide a %s.'));
or else ,if you want give common message for required fields,
$this->form_validation->set_message('required', 'required');
Hope you understand.
Related
So I followed this tutorial to learn how to upload images with Laravel using Vue: Image upload and validation using Laravel and VueJs
Everything works fine, but I want to make the image upload optional. Now the custom validation fails for the AppServiceProvider. if it does not have any input then i get this error
trying to access an attribute inside an array that does not exist. Undefined offset: 1
I could avoid the error by asking
if (request('image'))
In the controller and applying the validation for the other fields only if no image is given. However, this gets incredibly messy.
So I am looking for a way to get the custom validation rule working if there is no input. Or is that the wrong way?
Here is the custom validation rule:
public function boot()
{
Validator::extend('image64', function ($attribute, $value, $parameters, $validator) {
$type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1];
if (in_array($type, $parameters)) {
return true;
}
return false;
});
Validator::replacer('image64', function($message, $attribute, $rule, $parameters) {
return str_replace(':values',join(",",$parameters),$message);
});
}
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);
In the example above, the email field will only be validated if it is present in the $data array.
Reference: Conditionally Adding Rules
Laravel provides a validation called 'nullable' in case other validation rules should not be run if the given value is null: A Note On Optional Fields
I am trying to create a custom validation to check if a file was uploaded in a form.
I looked at the custom errors docs but couldn't make it work.
I found this tutorial: Custom Error
In my controller I do this:
if($request->hasFile('file'))
$has_file = 1;
else
$has_file = 0;
$this->validate($request, ['file' => 'isuploaded']);
In App/ServiceProvider I added this:
Validator::extend('isuploaded', function($attribute, $value, $parameters, $validator) {
return ?;
});
What should I return here? How do I send the $has_file to the validator?
If the file field is required the validate will check it for you.
Assuming that your form file input has name="file", just:
$this->validate($request, [
'file' => 'required
]);
In this way if there is no file the validation will fail.
If this is not your case and you want to create the custom rules in Validator::extend you should write your own business logic to check if the file exists and just return true/false.
I am struggling with how to do validation with belongsToMany relationships. Namely, the classic recipes/ingredients relationship. I would like a recipe to always have an ingredient on create or edit. What would my validation look like in my RecipesTable? I have tried:
$validator->requirePresence('ingredients')->notEmpty('ingredients')
As well as
$validator->requirePresence('ingredients._ids')->notEmpty('ingredients._ids')
The second one works in that my form doesn't validate, but it does not add the error class to the input. I am setting up the input with a field name of ingredients._ids.
I am also having trouble with creating the data to pass to $this->post in my tests in order to successfully add a record in my test. My data in my test looks like:
$data = [
'ingredients' => [
'_ids' => [
'2'
]
];
And of course I'm doing the post in my test with $this->post('/recipes/add', $data);
I'm not passing the required rules for ingredients in my test.
I solved how to set up the validators. In the recipe Table validator:
$validator->add('ingredients', 'custom', [
'rule' => function($value, $context) {
return (!empty($value['_ids']) && is_array($value['_ids']));
},
'message' => 'Please choose at least one ingredient'
]);
However, the validation message was not being displayed on the form, so I'm doing a isFieldError check:
<?php if ($this->Form->isFieldError('ingredients')): ?>
<?php echo $this->Form->error('ingredients'); ?>
<?php endif; ?>
I'm using multiple checkboxes in my view file versus a multi-select.
And with that, I'm getting my validation message on the form.
As I thought, my tests fell into place once I figured out the validator. What I show above is indeed correct for passing data in the test.
I will have desired to add this answer as a comment of Kris answer but I do not have enough reputation.
Alternatively, to solve the issue with validation message not being displayed on the form, you can add these two line in your controller.
if(empty($this->request->data['ingredients']['_ids']))
$yourentity->errors('ingredients', 'Please choose at least one ingredient');
I have a simple contact form with several required fields which is working fine. I am trying to add reCaptcha to the form for some added spam protection.
I have the reCaptcha displaying on the form correctly, I have my keys installed. In my controller I can call the recaptcha_check_answer method and get back valid responses. I have all of the files installed and configured correctly as I can use the methods from the recaptcha class and get back good responses.
My issue is that I would like to have an invalid reCaptcha trigger a CI form_validation error but I have spent alot of time on this and cannot get it to trigger. I am pretty new to CI so pardon my ignorance if this is something easy.
I have tried to throw a form_validation error when the is_valid response comes back NULL. If NULL then I tried to do the following:
$this->form_validation->set_message('recaptcha_response_field', 'reCaptcha', lang('recaptcha_incorrect_response'));
echo form_error('recaptcha_response_field');
Here is what the reCaptcha API responses look like for Valid and Invalid captcha's:
Valid = stdClass Object ( [0] => is_valid [1] => error [is_valid] => 1 )
Invalid = stdClass Object ( [0] => is_valid [1] => error [is_valid] => [error] => incorrect-captcha-sol )
Here is the code I have in my Controller:
class Contact extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->library('recaptcha');
$this->recaptcha->set_key ('MY_PUBLIC_KEY_HERE' ,'public');
$this->recaptcha->set_key ('MY_PRIVATE_KEY_HERE' ,'private'); // For private key
// Is this a Form Submission?
if (!empty($_POST))
{
// LOAD VALIDATION AND SET RULES
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('first_name', 'First Name', 'required');
$this->form_validation->set_rules('last_name', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('recaptcha_response_field', 'reCaptcha', 'required|recaptcha_check_answer');
$this->_resp = $this->recaptcha->recaptcha_check_answer ( $this->input->ip_address(), $this->input->post('recaptcha_challenge_field',true), $this->input->post('recaptcha_response_field',true));
// If the reCaptcha doesnt match throw an form_valiation Error
if ($this->_resp->is_valid == '')
{
$this->form_validation->set_message('recaptcha_response_field', 'reCaptcha', lang('recaptcha_incorrect_response'));
echo form_error('recaptcha_response_field');
}
if ($this->form_validation->run() !== FALSE)
{
// SUCCESS NO ERRORS - SEND EMAIL DATA AND RETURN TO HOME
$this->load->library('email'); // LOAD EMAIL LIBRARY
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';
$config['charset'] = 'utf-8';
$config['wordwrap'] = TRUE;
$this->email->initialize($config);
$this->email->from($this->input->post('email'), $this->input->post('first_name').' '.$this->input->post('last_name'));
$this->email->to('jassen.michaels#gmail.com');
$this->email->cc('');
$this->email->bcc('');
$this->email->subject('Contact Email From Spider Design Website');
$this->email->message(
'First Name: '.$this->input->post('first_name')."\r\n".
'Last Name: '.$this->input->post('last_name')."\r\n".
'Company: '.$this->input->post('company')."\r\n".
'Location: '.$this->input->post('location')."\r\n"."\r\n".
'I am interested in learning: '."\r\n"."\r\n".
'Information Architecture: '.$this->input->post('information_architecture')."\r\n".
'Web Design: '.$this->input->post('web_design')."\r\n".
'Graphic Design: '.$this->input->post('graphic_design')."\r\n".
'Email Marketing: '.$this->input->post('email_marketing')."\r\n".
'Social Media: '.$this->input->post('social_media')."\r\n".
'Content Management: '.$this->input->post('content_management')."\r\n".
'Search Engine Optimization: '.$this->input->post('seo')."\r\n".
'Web Traffic Analytics: '.$this->input->post('wta')."\r\n"."\r\n".
'Preferred Method of Contact: '."\r\n".
'Phone: '.$this->input->post('phone')."\r\n".
'Email: '.$this->input->post('email')."\r\n"."\r\n".
'Comments: '."\r\n".
$this->input->post('comments')
);
//$this->email->send();
//$this->load->helper('url');
//redirect('http://sdi.myspiderdesign.com/fuel');
}
}
// Not a form submission, load view
$this->load->helper('form');
$this->load->view('include/spider_header');
$this->load->view('contact'); // Content Area
$this->load->view('include/spider_footer'); // Footer
}
}
I have commented out the redirects and contact email at the bottom of the form until I can troubleshoot this issue.
Thanks in advance for all your help!
I used the callback_ function within the form_validation library. Setup an additional function inside the controller that made the API call and if the captcha did not pass it would throw a validation_error.
Please please please can someone help me
$this->load->library('form_validation');
$this->load->helper('cookie');
$data = array();
if($_POST) {
// Set validation rules including additional validation for uniqueness
$this->form_validation->set_rules('yourname', 'Your Name', 'trim|required');
$this->form_validation->set_rules('youremail', 'Your Email', 'trim|required|valid_email');
$this->form_validation->set_rules('friendname', 'Friends Name', 'trim|required');
$this->form_validation->set_rules('friendemail', 'Friends Email', 'trim|required|valid_email');
// Run the validation and take action
if($this->form_validation->run()) {
echo 'valid;
}
}
else{
echo 'problem';
}
Form validation is coming back with no errors can cany one see why?
Is it actually echoing 'valid'? (you're missing an apostrophe there, btw)
The code you show will only echo 'problem' when $_POST is false, not when validation fails.
Without knowing more, it may be as simple as:
// Run the validation and take action
if($this->form_validation->run()) {
echo('valid');
} else {
echo('invalid');
}
Try like this without checking if $_POST is set - not really needed:
//validation rules here
//
if ($this->form_validation->run() == TRUE) {
//do whatever that shall be run on succeed
} else {
$this->load->view('form'); //load the form
}
Read more about the controller part here