CakePHP Validation Rule Error - php

I've go some validation functions written to check if the user's email exists in the system.
I am getting the following error
Notice (8): Undefined offset: 0 [CORE/cake/libs/model/model.php, line 1122]
This is the code which causes the error
'email' => array(
'emailRule-1' => array(
'rule' => 'email',
'message' => 'email format is incorrect',
'last' => true
),
'emailRule-2' => array(
'rule' => 'checkEmailExist',
'message' => 'email already exists in the system'
)
),
And rule2 seems to be responsible for the error, and here is the rule2:
function checkEmailExist($emailAddress, $user_id){
$this->recursive = -1;
if($user_id > 0){
$user = $this->read(array('email'), $user_id);
if($emailAddress == $user['User']['email'])
return true;
}
$result = $this->find('count', array('conditions' => array('User.email' => $emailAddress)));
return $result > 0 ? false : true;
}

Why not do it like this?
public $validate = array(
'email' => array(
'rule' => array('email', 'isUnique')
)
);
You might want to split it up into two separate rules to apply your own error messages, but this should work just fine.

Did you try to debug what $emailAddress contains?
I bet this is an array^^
function checkEmailExist($emailAddress, $user_id){
$this->recursive = -1;
$email = array_shift(emailAddress);
...
you need to get the child element first
so remember: always a good idea to use debug() or pr() to debug your variables first.

Related

CakePHP 3: How to use custom pagination?

I don't succeed in using the pagination with a custom query. I follow exactly what's in the doc, but it doesn't work. The point is to paginate a list of records, having the flag 'valid' to 'Y' or 'N'.
In the controller:
if (!isset($this->request->query['valid']) || $this->request->query['valid'] == '')
$allFilters['valid'] = 'N';
else
$allFilters['valid'] = 'Y';
$this->paginate = ['finder' => ['curnames' => $allFilters]];
$data = $this->paginate($this->Names)->toArray();
In the model:
public $paginate = ['finder' => 'curnames', 'limit' => 25, 'order' => ['Names.id' => 'asc']];
public function findCurnames(Query $query, array $options) {
$query->where([
'valid' => $option['valid']
]);
return $query;
}
When I execute the code, I get a Cake\Network\Exception\NotFoundException exception. What I am missing?
Update: The version is 3.3. The error is triggered when this is executed:
$data = $this->paginate($this->Names)->toArray();
Update : In the controller, I've change the line
$this->paginate = ['finder' => ['curnames' => $allFilters]];
to
$paginate = ['finder' => ['curnames' => $allFilters]];
and the error doesn't pop up anymore. But the condition filtering on the 'valid'='Y' or 'N' is not taken into account. So it still doesn't work.
I got the answer. The error comes from a typo. Correct code should be
'valid' => $options['valid']
Options with a 's'.
Now it works.
Isn't it easier to do something like this (without any custom finder method):
if ($this->request->getQuery('valid', '') == '')
$valid = 'N';
else
$valid = 'Y';
$this->paginate = [
'limit' => 25,
'order' => ['Names.id' => 'asc']
];
$query = $this->Names->find('all')
->where([
'valid' => $valid
]);
$data = $this->paginate($query)->toArray();

Validating Top Level Domains with Zend 1

I am having a problem with Validating Top Level Domains. Basically, anything with .tech as the TLD is failing the email validation.
I have inherited this project and don't know Zend very well but I have traced the problem back to the hostname not being valid here is the code on GitHub;
// Match hostname part
if ($this->_options['domain']) {
$hostname = $this->_validateHostnamePart();
}
$local = $this->_validateLocalPart();
// If both parts valid, return true
if ($local && $length) {
if (($this->_options['domain'] && $hostname) || !$this->_options['domain']) {
return true;
}
}
return false;
Now, I have some local code here;
class Form_InviteToSpaceForm extends Twitter_Bootstrap_Form_Horizontal
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
$this->setAction('/team');
$this->addElement('textarea', 'email', array(
'label' => 'Email addresses',
'dimension' => 10,
'required' => true,
'placeholder' => "person1#email.com person2#email.com",//line breaks don't work on placeholders, have to force line wrap with spaces
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'NotEmpty'),
array('validator' => 'EmailAddress', 'options' => array('messages' => array('emailAddressInvalidFormat' => 'Incorrect email address specified.')))
)
));
If I comment out the line with the last array('messages' => array('emailAddressInvalidFormat' => 'Incorrect email address specified.'))) then this whole validation is avoided. But I don't want to avoid using this. I just want to be able to extend and add .tech or whatever else comes up from genuine clients. How can I do this with Zend?
You can write custom validator extended from Zend validator
class My_Validate_Hostname extends Zend_Validate_Hostname
{
public function __construct($options = array())
{
parent::__construct($options);
$this->_validTlds = array_merge($this->_validTlds, array('tech'));
}
}
and pass it to email validator
$emailValidator = new Zend_Validate_EmailAddress(array('messages' => array('emailAddressInvalidFormat' => 'Incorrect email address specified.')));
$emailValidator->setHostnameValidator(new My_Validate_Hostname());
....
$this->addElement('textarea', 'email', array(
'label' => 'Email addresses',
'dimension' => 10,
'required' => true,
'placeholder' => "person1#email.com person2#email.com",//line breaks don't work on placeholders, have to force line wrap with spaces
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'NotEmpty'),
)
))->addValidator($emailValidator);

Error message from form validation using a model method for custom rule

I need to display an error message for a custom validation rule, but I can't get to do it.
This is the validation rule:
$config = array(
....,
array(
'field' => 'general_sales_subaccount',
'label' => 'General Sales Subaccount',
'rules' => array(
'required',
'numeric',
array(
$this->subaccounts_model,
'is_valid'
)
),
)
);
$this->form_validation->set_rules($config);
And now this is the referenced model method:
public function is_valid($subaccount)
{
$subaccount_num_digits = $this->preferences->get('subaccount_num_digits');
if (strlen($subaccount) != $subaccount_num_digits ) {
$this->form_validation->set_message('is_valid', "The number of digits in %s doesn't match the length set to " . $subaccount_num_digits);
return false;
}
return true;
}
The rule seems to work, but it displays this error message:
Unable to access an error message corresponding to your field name (Anonymous function).
Any ideas?
You can't get an error message because you don't setup functions name. You may change your rule function like below:
$config = array(
....,
array(
'field' => 'general_sales_subaccount',
'label' => 'General Sales Subaccount',
'rules' => array(
'required',
'numeric',
array( //you may get all in another array
'is_valid', // and tell codeigniter your functions name
array(
$this->subaccounts_model,
'is_valid'
)
)
),
)
);
$this->form_validation->set_rules($config);

How can we validate multiple fields with one validation in cakePHP 2.0?

how can we check firstname and last name is unique validation in cakePHP ?
record1:
first name :raj
last name: kumar
if we enter same name in input field , it should show validation message "Record alredy Exists".
i know how to validate single field validation.
how to validate that the combination of first_name and last_name is unique?
Please help me in this.
Thanks in Advance
You will want to setup a custom validation rule for testing that the 'full name' is unique. For example, in your model add a new method for validation like this:-
public function validateUniqueFullName(array $data) {
$conditions = array(
'first_name' => $this->data[$this->alias]['first_name'],
'last_name' => $this->data[$this->alias]['last_name']
);
if (!empty($this->id)) {
// Make sure we exclude the current record.
$conditions[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
}
return $this->find('count', array('conditions' => $conditions)) === 0;
}
Then add the new validation rule to the model's $validate property:-
public $validate = array(
'first_name' => array(
'unique' => array(
'rule' => 'validateUniqueFullName',
'message' => 'Not unique'
)
)
);
Where 'rule' => 'validateUniqueFullName' instructs Cake to use the new validation rule to check that the name is unique.
You'll probably want to tweak/improve the above custom rule to meet your exact requirements but it should put you on the right track.
Try this way
public $validate = array(
'facebook_link' => array(
'rule' => array('customValidation','facebook_link'),
'message' => 'Please enter facebook link.'
),
'twitter_link' => array(
'rule' => array('customValidation','twitter_link'),
'message' => 'Please enter twitter link.'
)
);
function customValidation($data , $filed) {
if(empty($data[$filed])) {
return false;
}
return true;
}

Codeigniter: Firm unique validation not working

I have tried almost everything in my knowledge and found on net but nothing works. What I am trying to do is while adding new record I want to check whether the field value is already in database table or not. If not than add else throw error message.
I have tried also with is_usnique but than it is not allowing to modify data since it is considering that form value is exists.
Table name is positions
Coloumn name is position
Input field name is position
I have tried below code in my Controller
public function _unique_poscode()
{
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$poses = $this->positions_model->get();
if (count($poses)) {
$this->form_validation->set_message('_unique_poscode', '%s should be uinique');
return FALSE;
}
return TRUE;
}
And set rules in my Model as below
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|callback__unique_poscode|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
but no matter whatever I do it is not working and adding record even if it is exists in table.
Can anyone help me to fix this issue? Thanks a lot.
you are missing parameter
public function _unique_poscode( $p )
{
$this->form_validation->set_message('_unique_poscode', '%s should be uinique');
$q = $this->db->get_where('positions', array('position' => $p));
return ($q->num_rows() > 0) ? TRUE : FALSE;
}
and in rules
...|callback__unique_poscode|trim
and how it is done by codeigniter is as one of rules, please see this for more
is_unique[table.column]
Simply add this to rules and check.
is_unique[TABLENAME.COLUMNNAME]
According to your one it should be,
is_unique[positions.position]

Categories