CakePHP $this->Plan->validates() Validation from non-model form - validation

I've been at this most of the day now, and I cannot get this working for the life of me (well I can get it 1/2 working but not fully correctly).
Basically, I am trying to use Validation on a search form field like so:
if(isset($search['ApplicantAge']) && !empty($search['ApplicantAge'])) {
if ($this->Plan->validates()) {
$ApplicantAge = $search['ApplicantAge'];
}
}
And here is my model code:
...
'ApplicantAge' => array(
'required' => true,
'allowEmpty' => false,
'rule' => 'numeric',
'message' => 'A valid Age is required. Please enter a valid Age.'),
...
The validation is working BUT when I enter a number (numeric), it displays my error! And when it's blank NO error displays, and when I enter letters it seems to work : ( ??
Does anyone know a trick to this odd behavior?

Try using the 'notEmpty' rule instead of the required/allowEmpty stuff.
'ApplicantAge' => array(
'applicant-age-numeric'=> array(
'rule' => 'numeric',
'message' => 'A valid Age is required. Please enter a valid Age.'
),
'applicant-age-not-empty'=> array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank'
)
)

firstly why are you using the field 'ApplicantAge' when the conventions say its should be lower case under scored?
to answer your question the best way to do validation like that is http://book.cakephp.org/view/410/Validating-Data-from-the-Controller
the other option is to do $this->Model->save($data, array('validate' => 'only'));

The manual did not assist me at all : (
But your suggestion on the validate => only array seems to have done the trick. This is how I got it working:
plans_controller.php
if (isset($search['ApplicantAge'])) {
$this->Plan->save($search, array('validate' => 'only'));
if ($this->Plan->validates($this->data)) {
$ApplicantAge = $search['ApplicantAge'];
}
}
plan.php (model)
var $validate = array(
'ApplicantAge' => array(
'applicant-age-numeric' => array(
'rule' => 'numeric',
'message' => 'A valid Age is required. Please enter a valid Age.'),
'applicant-age-not-empty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank'),
),
Now, if no data is entered in the ApplicateAge field, the proper message is displayed. And if a non-numeric is entered, the correct message is also displayed.
This was a lot more challenging than I thought it would be!

For the record, I'll make a correction to my earlier accepted post. Little did I know the validate => only on the save() was actually still saving data to my plans table.
I was able to get it working using set(). Here is the code that completely solved the problem:
plans_controller.php
if (isset($search['ApplicantAge'])) {
$this->Plan->set($this->data);
if ($this->Plan->validates()) {
$ApplicantAge = $search['ApplicantAge'];
}
}
plan.php (model):
var $validate = array(
'ApplicantAge' => array(
'applicant-age-numeric' => array(
'rule' => 'numeric',
'message' => 'A valid Age is required. Please enter a valid Age.'),
'applicant-age-not-empty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank'),
)

Related

How to dynamically validate form field in symfony 2.3

I need to validate input field depending on options i pass to buildForm()
And i have this code i glued together from googling around.
However in controller
$form->isValid()
passes with values that are outside the range:
$builder->add('limit', 'integer', array(
'constraints' => [
new Assert\Range(array(
'min' => $options['min'],
'max' => $options['max'],
'minMessage' => 'min error message',
'maxMessage' => 'max error message',
))
],
));
How do I dynamically validate the input?
UPDATE:
Symfony2 validation using Assert annotation does not work same issue. Will have to write a custom validator.
You can do something basic like this:
if ($option['condition'] === 'whatever') {
$limtiConstraint = new Assert\Range(array(
'min' => $options['min'],
'max' => $options['max'],
'minMessage' => 'min error message',
'maxMessage' => 'max error message',
));
} else {
// $limtiConstraint = 'other constraint with other options'
}
$builder->add('limit', 'integer', array(
'constraints' => [$limtiConstraint]
));
Or if you want to modify the limits, you can use the ternary operator:
'min' => $options['condition'] ? $options['min'] : $options['other_min'],

what would the following form validation rule mean ? I want a logic that even if one of the form posts are set...it should be allowed

$this->form_validation->set_rules('newusername', 'newfullname', 'newcity','newemail');
// is the set_rules correct. I want that if any one input field with above names are set. It should pass the validation . Please help me if there are any corrections.
May be you should read the manual again. If you want at least one of them filled, you'll need to write your own validation.
Using the following rules:
public $rules = array(
'newusername' => array(
'field' => 'newusername',
'label' => 'New User Name',
'rules' => 'trim|xss_clean|callback_needone'
),
'newfullname' => array(
'field' => 'newusername',
'label' => 'New Full Name',
'rules' => 'trim|xss_clean|callback_needone'
),
'newcity' => array(
'field' => 'newcity',
'label' => 'New City',
'rules' => 'trim|xss_clean|callback_needone'
),
'newemail' => array(
'field' => 'newemail',
'label' => 'New Email',
'rules' => 'trim|xss_clean|callback_needone'
)
)
in your controller you have to write
public function needone(){
if ( empty($this->input->post('newusername')) && empty($this->input->post('newfullname')) && empty($this->input->post('newcity')) && empty($this->input->post('newmail')) ) {
$this->form_validation->set_message('needone', 'At least one field must be entered');
return FALSE;
}
return TRUE;
}
Put the rule on any of the form's fields, or all of them to hilite those who are in the required group, it's up to you.
Each input field in your form, requires it's own validation rules. Which should look like this;
$this->form_validation->set_rules('field name', 'human name', 'rules');
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules
So, you would have 4 set_rules functions, like this;
$this->form_validation->set_rules('newusername', 'New username', 'trim|xss_clean|required');
$this->form_validation->set_rules('newfullname', 'New full name', 'trim|xss_clean|required');
$this->form_validation->set_rules('newcity', 'New City', 'trim|xss_clean|required');
$this->form_validation->set_rules('newemail', 'New Email', 'trim|xss_clean|required');
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#cascadingrules
Here's a rule reference, all the available rules;
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#rulereference
Now, to check if ANY of the items are set, I would do this;
if ($this->input->post('newusername') OR $this->input->post('newusername') OR $this->input->post('newusername') OR $this->input->post('newusername'))
{
// One of them is set
}
else
{
// Nothing is set
}

CodeIgniter custom validation errors for each rule per each field

I'm using CodeIngiter 2.1 and I wanna define custom validation errors for each rule per each field. The fields are as follows.
array(
'field' => 'firstname',
'rules' => 'required',
'error' => 'This field cannot be empty.'
),
array(
'field' => 'email',
'rules' => 'required',
'error' => 'The email cannot be empty.'
)
But In CodeIgniter only one error message is defined for one rule. So how to override that one and Please suggest some solutions for getting different errors for perticular field. The work is more appreciated.
Try using the CI function :
set_message();
All of the native error messages are located in the following language file:
language/english/form_validation_lang.php
To set your own custom message you can either edit that file, or use the following function:
$this->form_validation->set_message('rule', 'Error Message');
for more about set_message here
Hope it will help;
I recently made this custom error message option for my codeigniter 3.0-dev applicaiton. Hope this helps anyone out there.
https://gist.github.com/abdmaster/7287962
To use it (example),
$this->form_validation->set_rules('name','Name','required|alpha',array('required' => 'Please fill the field %s .');`
It will work with Base models like jamierumbelow's MY_Model. In your model, you do something like this:
public $validate = array(
'display_name' => array(
'field' => 'display_name',
'label' => 'Display Name',
'rules' => 'trim|required|xss_clean|valid_fullname|is_unique[users_model.display_name]',
'error_msg' => array(
'is_unique' => 'The name in %s is already being used by someone.',
),
),
);
Rest are how we are use normally. Hope these examples are enough.
I haven't tried in v2.1.x but hopefully this will work. Maybe have to do some minor adjustments.

CakePHP when using $model->save() validate rules and skip other rules

I'm using CakePHP 2.0 and I have a model that I use validation on it like this:
var $validate = array(
'title' => array(
'unique_rule'=>array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This title has already been taken.'
),
'required_rule'=>array(
'required' => true,
'allowEmpty' => false,
'message' => 'The title field is required.'
)
)
);
, and in the controller I have an edit action and I use $model->save() to save date from $this->request->data, but it fails the isUnique validation rule, although it is not a new record insertion.
Is there any way to specify that it is an existing record, not a new one ?
If I got the question right you have to set the model's ID before calling $model->save(); so cakephp knows it's an update.
See http://book.cakephp.org/2.0/en/models/saving-your-data.html:
"Creating or updating is controlled by the model’s id field. If $Model->id is set, the record with this primary key is updated. Otherwise a new record is created:"
<?php
// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);
// Update: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);
your validation array is wrong you haven't set a rule for 'required_rule' wich might trigger the isUnique error message.
var $validate = array(
'title' => array(
'unique_rule'=>array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This title has already been taken.',
'last' => true
),
'required_rule'=>array(
'rule' => array('notEmpty'),
'message' => 'The title field is required.'
)
)
);
Also remember that using required=>true will NOT result check for actual data, it only wants the field to be present in the data-array and "" is also considered as present

cakePHP optional validation for file upload

How to make file uploading as optional with validation?
The code below validates even if i didn't selected any file.
I want to check the extension only if i selected the the file.
If i am not selecting any file it should not return any validation error.
class Catalog extends AppModel{
var $name = 'Catalog';
var $validate = array(
'name' => array(
'rule' => '/^[a-z0-9 ]{0,}$/i',
'allowEmpty' => false,
'message' => 'Invalid Catalog name'
),
'imageupload' => array(
'rule' => array('extension',array('jpeg','jpg','png','gif')),
'required' => false,
'allowEmpty' => true,
'message' => 'Invalid file'
),
);
}
thanks in advance
"I assign $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"
So by the time you save your data array, it looks something like this I assume:
array(
'image' => 'foobar',
'imageupload' => array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
)
Which means, the imageupload validation rule is trying to work on this data:
array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
I.e. the value it's trying to validate is an array of stuff, not just a string. And that is unlikely to pass the specified validation rule. It's also probably never "empty".
Either you create a custom validation rule that can handle this array, or you need to do some more processing in the controller before you try to validate it.
Concept:
In Controller, before validating, or saving (which does validation automatically by default) check if any file is uploaded. If not uploaded, then unset validator for the file field.
Sample code:
Controller
// is any image uploaded?
$isNoFileUploaded = ($this->request->data['Model']['field_name']['error'] == UPLOAD_ERR_NO_FILE) ? true : false ;
if ($isNoFileUploaded) {
$this->Model->validator()->remove('field_name');
}
Notes:
This solution comes under preprocessing as one of the two alternative approaches (preprocessing in controller, custom validation in model) suggested by #deceze's answer

Resources