Codeigniter: Form validation is_unique error not showing - php

I am using the below line to check my add user form to check if the email address does not exist in my database I have a feeling that it is working fine but I am unable to get any error messages.
$this->form_validation->set_rules('userEmail','E-Mail', 'required|valid_email|trim|max_length[99]|xss_clean|is_unique[users.email]');
In my view I have <?php echo validation_errors(); ?>
My controller is formatted as per below:
if($this->form_validation->run() === TRUE)
{
$userData = array(
'fName' => $this->input->post('userFirstName', TRUE),
'lName' => $this->input->post('userLastName', TRUE),
'email' => $this->input->post('userEmail', TRUE),
'password' => sha1($this->input->post('userPassword', TRUE))
);
$this->db->escape($userData);
$this->user_model->addUser($userData);
}

I changed my controller to the following:
$this->form_validation->set_rules('userEmail','E-Mail', 'required|valid_email|trim|max_length[99]|xss_clean|is_unique[users.email]');
$this->form_validation->set_rules('userPassword','Password', 'required|trim|max_length[99]|xss_clean');
if($this->form_validation->run() === TRUE)
{
$userData = array(
'fName' => $this->input->post('userFirstName', TRUE),
'lName' => $this->input->post('userLastName', TRUE),
'email' => $this->input->post('userEmail', TRUE),
'password' => sha1($this->input->post('userPassword', TRUE))
);
$this->db->escape($userData);
$this->user_model->addUser($userData);
}
$data['contentMangement'] = $this->options_model->systemOptions();
$data['pageTitle'] = 'Add User';
$this->load->view('_assets/header', $data);
$this->load->view('addUser', $data);
$this->load->view('_assets/footer');
}

Just use the is_unique predefined validation rule. Pass the table name and column name for the email column.
$this->form_validation->set_rules('userEmail','E-Mail', 'required|valid_email|trim|max_length[99]|xss_clean|is_unique[users.email]');

we must add to table name for is_unique
in my way for exp.
array(
'field' => 'email',
'label' => 'email',
'rules' => 'trim|required|valid_email|is_unique[users.email]',
'errors' => array('required' => 'Please enter a %s.','valid_email' => 'Please enter a valid %s.','is_unique' => 'email already exist.')
),
hope you under stand.

Related

Validation always return mesasge 'required is not a valid rule' | Codeigniter 4

I made the validation in the config / validation.php with references from the official documentation https://codeigniter4.github.io/userguide/libraries/validation.html like this:
class Validation
{
....
public $user = [
'name' => [
'rules' => 'required'
],
'email' => [
'rules' => 'valid_email|required',
'errors' => [
'valid_email' => 'E-mail is not valid',
'required' => 'E-mail is required'
]
]
];
}
and then I call it on my controller like this:
....
class User extends ResourceController
{
public function create()
{
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
$country = $this->request->getPost('country');
$province = $this->request->getPost('province');
$city = $this->request->getPost('city');
$day_of_birth = $this->request->getPost('day_of_birth');
$password = $this->request->getPost('password');
$phone_number = $this->request->getPost('phone_number');
$photo = $this->request->getPost('photo');
$data = [
'name' => $name,
'email' => $email,
'country' => $country,
'province' => $province,
'city' => $city,
'day_of_birth' => $day_of_birth,
'password' => $password,
'phone_number' => $phone_number,
'photo' => $photo
];
$validate = $this->validation->run($data,'user');
$errors = $this->validation->getErrors();
if($errors){
return $this->fail($errors);
}
return $this->respond($data);
}
}
when i tested it using postman, I get a return like this:
the validation works fine if I do it in the controller, but I want to declare the validation in validation.php, someone please help me, whatever I write in validation.php then i call using $this->validation->run($data,'name') always returns the same
You have not added the error message in the name required validation so maybe it's the problem so you must add an error message to the name.
Because validation in the message is important . Without any error messages, how can the user know what is the problem in the form.
Here is the customized function or sample of validation. change your function be like.
class Validation
{
public $user = [
'name' => [
'rules' => 'required',
'errors' => [
'required' => 'Name is required.'
]
],
'email' => [
'rules' => 'required|valid_email',
'errors' => [
'valid_email' => 'E-mail is not valid',
'required' => 'E-mail is required'
]
],
];
}

Email Validation in cakephp Model

I have the below setup of validation rules. For some reason, 'on' => 'create' block doesn't work. The conditions to be implemented are standard create / modify regarding email. Also, in edit section, I'm getting the error from 'on' => 'create' block.
How to validate the email? I'm using CakePHP v 2.6.1.
public $validate = array(
'email' => array(
'required' => array(
'rule' => array('email'),
'message' => 'Kindly provide your email for verification.'
),
'maxLength' => array(
'rule' => array('maxLength', 255),
'message' => 'Email cannot be more than 255 characters.'
),
'editunique' => array(
'rule' => array('editunique'),
'message' => 'Provided Email address already exists.',
'on' => 'update'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'Provided Email already exists.',
'on' => 'create'
)
)
);
public function editunique($email) {
// email should be one and of the logged in user only.
if ($this->find('count', array(
'conditions' => array(
$this->alias . '.id <>' => $this->data[$this->alias]['id'],
$this->alias . '.email' => $email
)
)) > 1) {
return false;
}
}
Also, I'm not getting the $this->data[$this->alias]['id'] value.
My Controller has the following section:
if ($this->Client->hasAny(array('Client.id' => base64_decode(trim($this->request->query['client_id']))))){
if ( $this->request->is('ajax') && $this->request->is('post') ){
$this->Client->create();
$this->Client->id = base64_decode(trim($this->request->query['client_id']));
$this->Client->set($this->request->data);
// validate
if($this->Client->validates()) {
// save the data after validation
if($this->Client->save($this->request->data)){
}
}
}
}
I think you are misunderstanding what Cake's isUnique rule checks for and as a result over complicating things. Cake defines isUnique as:-
The data for the field must be unique, it cannot be used by any other rows
When it checks if a value is unique it is smart enough to exclude existing data of the current row (which appears to be what you are attempting to do with your editunique rule).
So you just need your validation rules to look like:-
public $validate = array(
'email' => array(
'required' => array(
'rule' => array('email'),
'message' => 'Kindly provide your email for verification.'
),
'maxLength' => array(
'rule' => array('maxLength', 255),
'message' => 'Email cannot be more than 255 characters.'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'Provided Email already exists.'
)
)
);
This removes the editunique rule and drops the on condition of your unique rule.
As of cakephp 3.0 in the entities table it should look something like this
namespace App\Model\Table;
public function validationDefault($validator)
{
$validator
->email('email')
->add('email', 'email', [
'rule' => [$this, 'isUnique'],
'message' => __('Email already registered')
])
->requirePresence('email', 'create')
->notEmpty('email', 'Email is Required', function( $context ){
if(isset($context['data']['role_id']) && $context['data']['role_id'] != 4){
return true;
}
return false;
});
return $validator;
}
}
function isUnique($email){
$user = $this->find('all')
->where([
'Users.email' => $email,
])
->first();
if($user){
return false;
}
return true;
}

CodeIgniter - Captcha callback validation not working

I'd like some help please.
This is the array that holds all the validation on a contact form
class Contact_Form extends CI_Controller
{
private $_validation = array(
'fullname' => array(
'field' => 'fullname',
'label' => 'Fullname',
'rules' => 'trim|required|max_length[255]'
),
'email' => array(
'field' => 'email',
'label' => 'Email Address',
'rules' => 'trim|required|max_length[255]|valid_email'
),
'phone' => array(
'field' => 'phone',
'label' => 'Phone',
'rules' => 'trim|max_length[10]|integer'
),
'message' => array(
'field' => 'message',
'label' => 'Message',
'rules' => 'trim|required'
),
'captcha' => array(
'field' => 'captcha',
'label' => 'Security Code',
'rules' => 'trim|required|callback_validate_captcha'
)
);
// This is the part where I validate my contact form inside a method
$this->load->library('form_validation');
$this->form_validation->set_rules($this->_validation);
if ($this->form_validation->run() === true) {
echo 'works!';
}
This is the callback function that validates the captcha
public function callback_validate_captcha($str) {
$post_captcha = $this->input->post('captcha');
$set_captcha = $this->session->userdata('captcha');
if (strcmp($set_captcha, $post_captcha) !== 0) {
$this->form_validation->set_message('validate_captcha', '%s is wrong');
return false;
}
return true;
}
If i hit submit on an empty form I get the error that idicates that captcha is a required field, but if i submit a wrong code i don't get any error at all, which means that the callback is being ignored.
I tried to change my if statement
// change this (althought i feel its more correct)
if (strcmp($set_captcha, $post_captcha) !== 0)
// to this
if ($set_captcha != $post_captcha)
but the problem remains. Any ideas what's wrong?
you are making major mistake you have to make function validate_captcha instead of callback_validate_captcha.
Because callback is form keyword to call a function just try and bingo

Show the correct error validation messages

I have a page with 2 forms on it: a registration form and a login form. Each form has a submit button. Now I'm validating both forms, but for example if I press the submit button of the registration form I'd like only to show the error messages of the registration form and not of the login form. At the moment both error message are being shown. Is there a way around this?
<div class="grid-container">
<div class="grid-50 login">
<h3>Inloggen</h3>
<?php
$loginEmail = array('placeholder' => "Email", 'name' => "loginEmail");
$loginPassword = array('placeholder' => "Wachtwoord", 'name' => "loginPassword");
$loginSubmit = array('name' => "loginSubmit", 'class' => "btn", 'value' => "Inloggen");
$loginForgot = array('name' => "loginForgot", 'class' => "link", 'value' => "Wachtwoord vergeten?");
echo form_open('login/inloggen', array('class' => 'grid-100 formc'));
echo form_input($loginEmail);
echo form_password($loginPassword);
echo form_submit($loginSubmit);
echo form_submit($loginForgot);
echo form_close();
?>
<?php echo validation_errors('<p class="error">');?>
</div>
<div class="grid-50 login">
<h3>Registreren</h3>
<?php
$registerName = array('placeholder' => "Naam", 'name' => "registerName");
$registerEmail = array('placeholder' => "Email", 'name' => "registerEmail");
$registerPassword = array( 'placeholder' => "Wachtwoord", 'name' => "registerPassword");
$registerSubmit = array('name' => "registerSubmit", 'class' => "btn", 'value' => "Registreer");
echo form_open('login/register');
echo form_input($registerName, set_value('registerName'));
echo form_input($registerEmail, set_value('registerEmail'));
echo form_password($registerPassword);
echo form_submit($registerSubmit);
echo form_close();
?>
<?php echo validation_errors('<p class="error">');?>
</div>
Validation in the controller
$this->form_validation->set_rules('registerEmail', 'Email verkeerd', 'trim|required|valid_email');
$this->form_validation->set_rules('registerPassword', 'Password te kort', 'trim|required|min_length[4]');
it would be nicer if you create different rules for the login and for you're registration.
how?
create a Form_validation.php file on application/libraries
inside specify the rules for you're login and register example
$config = array(
'login_validation_rules'=>array(
array(
'field' => 'username',
'label' => 'The User Name',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'The Password',
'rules' => 'required'
)
),
'registration_validation_rules'=>array(
array(
'field' => 'email',
'label' => 'The Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'firstname',
'label' => 'The Firstname',
'rules' => 'required'
)
)
);
Then on you're controller you can catch what form they are submitting and what validation rules to use example
if($this->input->post('registerSubmit'))
{
if($this->form_validation->run('registration_validation_rules') == FALSE)
{
//error
}else{
//good
}
}elseif($this->input->post('loginSubmit')){
if($this->form_validation->run('login_validation_rules') == FALSE)
{
//error
}else{
//good
}
}
At the same time you're controller will not be cluttered with rules. makes reading easier you can read more of this on the Codigniter manual - validation config file
Do you use two submit in one page? try to make one to submit through javascript or jquery
be cause when you submit the submit it submit the whole page in some browsers
also try this show validate error for each fields
<?=form_error('loginEmail')?>
<?=form_error('registerPassword')?>

custom config file not working with form validation

i've set the validation rules in application/config/validation_rules.php and it looks like this
(short version)
$config = array(
'member/register' => array(
'field' => 'language',
'label' => 'language',
'rules' => 'required|min_length[5]|max_length[12]'
),
array(
'field' => 'email',
'label' => 'email',
'rules' => 'required|valid_email'
),
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|min_length[8]'
),
array(
'field' => 'verify_password',
'label' => 'password',
'rules' => 'required|min_length[8]|matches[password]'
));
and i'm calling it like this:
$this->config->load('validation_rules');
$this->form_validation->set_rules($config);
if($this->form_validation->run('member/register') == FALSE)
{
$page = array(
'meta_title' => 'member registration',
'load_page' => 'front/register_view'
);
$this->load->view('front/template', $page);
}
not only is the validation_errors() function not showing anything but i'm also getting this error:
Message: Undefined variable: config
update: (here is my controller)
class register extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
}
function index()
{
$this->config->load('validation_rules', TRUE);
$this->form_validation->set_rules($this->config->item('config', 'validation_rules'));
if($this->form_validation->run('member/register') == FALSE)
{
//validation doesnt pass, load view
$page = array(
'meta_title' => 'member registration',
'load_page' => 'front/register_view'
);
$this->load->view('front/template', $page);
}
else
{
$register_data = array(
'language' => $this->input->post('language'),
'email' => $this->input->post('email'),
'password' => md5($this->input->post('password')),
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
'phone' => $this->input->post('phone'),
'address' => $this->input->post('address'),
'address2' => $this->input->post('address2'),
'city' => $this->input->post('city'),
'state' => $this->input->post('state'),
'zipcode' => $this->input->post('zipcode'),
'gfname' => $this->input->post('gfname'),
'glname' => $this->input->post('glname'),
'gphone' => $this->input->post('gphone')
);
$this->session->set_userdata($register_data);
}
}
function package()
{
$page = array(
'meta_title' => 'Register Package',
'load_page' => 'register_package_view'
);
$this->load->view('includes/template', $page);
}
}
I encountered same problem but I managed to fix it by using following configuration:
In my application/config/form_validation.php:
$config = array(
"register" => array(
array(
"field" => "username",
"label" => "Username",
"rules" => "required"
)
)
);
Auto-load the custom config file "form_validation.php" inside application/config/autoload.php:
$autoload['config'] = array('form_validation');
In my controller:
// manually set rules by taking $config["register"] from form_validation.php
$this->form_validation->set_rules($this->config->item("register"));
// call run() without parameter
if ($this->form_validation->run() == FALSE) {
$this->load->view("user/register_test");
} else {
echo "Form content is correct";
}
I've tried calling the validator using $this->form_validation->run("register"), without using $this->form_validation->set_rules() function, but I got no luck. Setting the rules manually by retrieving it from config array in form_validation.php make my day.
In case you are extending the form_validation library, you need to pass the $config array to the parent constructor:
class MY_Form_validation extends CI_Form_validation {
/**
* constuctoooor
*/
function MY_Form_validation($config){
parent::__construct($config);
}
http://ellislab.com/forums/viewthread/181937/
It's also cleaner using the method outlined in the docs: http://ellislab.com/codeigniter%20/user-guide/libraries/form_validation.html#savingtoconfig to avoid calling $this->form_validation->set_rules(...);
/**
* This is the POST target for the password reset form above
* #return null
*/
public function submit(){
// perform validation //
if($this->form_validation->run() == FALSE){
// display error on sign-up page //
$this->session->set_flashdata("system_validation_errors", validation_errors());
redirect('member/forgot/password');
}
// more awesome code
}
$this->config->load('validation_rules');
$this->form_validation->set_rules($config);
should be:
$this->config->load('validation_rules', TRUE);
$this->form_validation->set_rules($this->config->item('validation_rules', 'validation_rules'));
Per the documentation:
// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"
$this->config->load('blog_settings', TRUE);
// Retrieve a config item named site_name contained within the blog_settings array
$site_name = $this->config->item('site_name', 'blog_settings');
Your rules are wrong, you forgot to put the validation group in an array:
$config['validation_rules'] = array(
'member/register' => array(
array(
'field' => 'language',
'label' => 'language',
'rules' => 'required|min_length[5]|max_length[12]'
),
array(
'field' => 'email',
'label' => 'email',
'rules' => 'required|valid_email'
),
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|min_length[8]'
),
array(
'field' => 'verify_password',
'label' => 'password',
'rules' => 'required|min_length[8]|matches[password]'
)
)
);

Categories