nothing is working except 'not empty' validation in cakephp - validation

I'm new to CakePHP. I'm validating my form, but the problem is that no validation is working except the not empty validation.
My model file is:
class User extends AppModel {
public $name = 'User';
public $validate = array(
'rule_name' => array(
'alphaNumeric' => array(
'rule' => 'Numeric',
'required' => true,
'message' => 'Letters and numbers only'
)
)
);
}
My View file is:
echo $this->Form->create('User');
echo $this->Form->input('rule_name',array('class'=>'form-control','autocomplete'=>'off'));
Please suggest how I can fix this.

General usage pattern adding a rule for a single field:
public $validate = array(
'fieldName1' => array(
'rule' => 'ruleName',
'required' => true,
'allowEmpty' => false,
'message' => 'Your Error Message'
)
);
Must be look at Data Validation in cakePHP

Related

CakePHP load model validation rule not working

I am loading a model in different controller.
Controller name in which I am loading different model is - "MembersController" and I am loading "Usermgmt" Model of "UsermgmtController".
"Usermgmt" Model has validation as following-
public $validate = array(
'email' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for email.'
),
'duplicate' => array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This email is already exist.'
),
'duplicate1' => array(
'rule' => 'email',
'message' => 'Please enter valid email.'
)
),
'firstname' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for first name.'
)
),
'username' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for user name.'
),
'duplicate' => array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This user is already exist.'
)
),
'password' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for password.'
)
),
'confirm_password' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for confirm password.'
),
'duplicate2' => array(
'rule' => 'matchpassword',
'on' => 'create',
'message' => 'Password must be same.'
)
)
);
And now I am applying and loading model in following way.
$this->loadModel('Usermgmt');
$this->Usermgmt->set($this->data);
if ($this->Usermgmt->validates()) {
if ($this->Usermgmt->save($data, true)) {
$userid = $this->Usermgmt->id;
$this->Session->setFlash('User has been added', 'success');
}
}
But validation are not working and it is inserting empty values.
try uses to load model
Example :
public $uses = array('Usermgmt');
You are using two different instances of $data. namely $this->data and $data
You should be validating the same set of data you want to save, like either of the two following examples, whichever holds your data.
$this->loadModel('Usermgmt');
$this->Usermgmt->set($data);
if ($this->Usermgmt->validates()) {
if ($this->Usermgmt->save($data, true)) {
$userid = $this->Usermgmt->id;
$this->Session->setFlash('User has been added', 'success');
}
}
Or
$this->loadModel('Usermgmt');
$this->Usermgmt->set($this->data);
if ($this->Usermgmt->validates()) {
if ($this->Usermgmt->save($this->data, true)) {
$userid = $this->Usermgmt->id;
$this->Session->setFlash('User has been added', 'success');
}
}
Unless you are requiring to do some other logic after validation and before saving you could do away with explicitly calling validates() and just save the data as save() will automatically validate the data for you. Also, I've noticed you are using $this->data, it looks like you are using CakePHP 2 in which case you need to use $this->request->data instead:-
$this->loadModel('Usermgmt');
if ($this->Usermgmt->save($this->request->data) !== false) {
$this->Session->setFlash('User has been added', 'success');
}
If this still fails then make sure you are not overriding beforeValidate() in your model in a way that would cause validation to break.

cakephp notempty and unique validation on field

I am working with cakephp. I need to add three validation on email field. First validation if email not given, second for valid email address, third if email address is given then it should be unique. Because its a signup form.
How I have add three validations on one field I try with the following code but it did not work for me.
public $validate = array(
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Invalid email address',
'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
)
),
'email' => array(
'rule' => 'isUnique',
'message' => 'Email already registered'
)
);
You have two identical indexes 'email' which PHP won't allow you. Change to something like:-
array(
'email' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Provide an email address'
),
'validEmailRule' => array(
'rule' => array('email'),
'message' => 'Invalid email address'
),
'uniqueEmailRule' => array(
'rule' => 'isUnique',
'message' => 'Email already registered'
)
)
);
Otherwise only one of your rules will be used.
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;
}
What version of Cakephp do you use?
Because I think if you use 2.3, it should be:
public $validate = array( 'email' => 'email' );
with the field email in your SQL table set as a primary key.

how can i set validation for multi select list in cakephp

I have a form with multi select box:
echo $this->Form->input('emp_id', array( 'options' => array( $arr),
'empty' => '(choose one)',
'div'=>'formfield',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Team Members',
'type' => 'select', 'multiple' => true,
'style' => 'width:210px; height:125px;'
));
I selected multiple values from this list box and click the SAVE button.
But it displays the validation message.
How can i solve this?
class TravancoDSRGroup extends AppModel {
var $name = 'TravancoDSRGroup';
var $useTable = 'dsr_group'; // This model uses a database table 'exmp'
var $validate = array(
'emp_id' => array(
'rule' => 'notEmpty',
'message' => 'The employee field is required'
)
);
}
This is the model code....
If it is possible...?
You don't have to explicitly specify
'type' => 'select'
if you set 'emps' from the controller, it will allow cake's automagic to work. just add
$this->set(compact('emps'));
Post output of debug($this->request->data) for better understanding of problem.
Have you defined hasMany or HABTM relationships to the emp ? To have multiple values saved you will have to define hasMany or HABTM relations, if you wish to save it as CSV then you will have to do the processing yourself in 'beforeSave'.

CakePHP validation always true

I've been struggling with this for the last hour or so, wondering if some fresh eyes can help.
Model
class User extends AppModel {
public $name = 'User';
public $validate = array(
'email' => array(
'valid' => array(
'rule' => 'email',
'message' => 'The email is not valid'
),
'required' => array(
'rule' => 'notEmpty',
'message' => 'Please enter an email'
)
)
);
}
Controller
class UserController extends AppController {
var $uses = array('User');
function index(){
$users = $this->User->find('all');
$this->set(compact('users'));
}
public function add() {
$this->set('title_for_layout', 'Add new user');
if(isset($this->data) && !empty($this->data)) {
$this->User->set($this->data);
$this->log($this->User->invalidFields(), "debug");
if($this->User->validates()){
if ($this->User->save($this->data)) {
$this->Session->setFlash("Added " . $this->data['User']['name']);
$this->redirect('index');
}
} else {
$this->Session->setFlash('There are errors with your form submit, please see below.');
}
}
}
}
View
<?php
echo $this->Form->create('User');
echo $this->Form->input('name', array('label' => 'Name'));
echo "<div class='clear'></div>";
echo $this->Form->input('email', array('label' => 'Email'));
echo "<div class='clear'></div>";
echo $this->Form->button('Reset', array('type' => 'reset'));
echo $this->Form->button('Add Useer', array('type' => 'submit'));
echo $this->Form->end();
?>
But I never get invalid fields for email? Have I missed something glaring?
If it makes any difference, this is a plugin Im developing so it doesnt sit directly in app/ but in app/Plugins
Thanks
EDIT: So I've been struggling with this for a while now, and still no joy. One thing I have noticed though, when I print out the model details (using var_dump($this->User) ), the [validate] array is empty. For example:
[validate] => Array
(
)
[validationErrors] => Array
(
)
Im presuming this is what the issue is, even though I have declared my $validate array, its somehow being overwritten? Anyone come across this before? Any solutions?
public $validate = array(
'email' => array(
'valid' => array(
'rule' => array('email'),
'message' => 'The email is not valid'
),
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter an email',
'allowEmpty' => false
)
)
);
Try adding rules as array and adding 'allowEmpty' key set to false on the required validation.
Damn! So simple. If I read the cookbook properly at http://book.cakephp.org/1.3/en/view/1114/Plugin-Models it would have told me that
If you need to reference a model within your plugin, you need to include the plugin name with the model name, separated with a dot.
Thus..
var $uses = array('Plugin.User');
works.. Hope this helps someone else!

CodeIgniter field validation based on condition

If the first field called sendEmail has value ="Yes" the rest of the fields are to be validated...
I have this set_rules defined in the form_validation.php file in the config folder..
$config = array(
array(
'field' => 'sendEmail',
'label' => 'Send Email',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
),
array(
'field' => 'first_name',
'label' => 'First Name',
'rules' => 'required'
),
array(
'field' => 'last_name',
'label' => 'Last Name',
'rules' => 'required'
)
);
but email, first_name and last_name fields are to be validated only if sendEmail has value="Yes".
Not sure how to do this, can someone please help me with this?
thanks
Do the conditions like this in your controller:
if ($this->input->post('sendEmail') == 'Yes'){
$this->form_validation->set_rules('email', 'Email', 'required');
... [etc]
}
The validation only runs when you call $this->form_validation->run(), so just write an if statement before that. Something like this:
if ($this->input->post("sendEmail") == 'Yes') {
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == FALSE)
{
// failed validated
}
else
{
// passed validation
}
} else {
// never attempted validation
}

Resources