Problem with cakephp validation - php

I have field in my model whose validation rules is shown below.
'message' => array(
'rule' => '/^[a-z0-9#.,&; ]{2,255}$/i',
'required' => true,
'allowEmpty' => false,
'message' => '(message field contains only a-z0-9#.,&; and is between 2 to 255 characters.).'
),
This works fine. When I add forwardslash(/) to the rule '/^[a-z0-9#.,&;/ ]{2,255}$/i' or '/^[a-z0-9#.,&;\/ ]{2,255}$/i'. then it does not work.
I appreciate any help.
Thanks.

That isn't a backslash, it is a forward slash.
So I don't know which slash you want to use, but one of these should work:
'/^[a-z0-9#.,&;\\ ]{2,255}$/i'
or
'/^[a-z0-9#.,&;\/ ]{2,255}$/i'

Related

Yii routing - how to put that controller

I need to perform routing for the following url schemas:
website.com/some-category-name
website.com/some-category-name/entryName
some-category-name will be variable - some name of category
How to configure routing for this? I need to enter previous controllers, for example:
website.com/account
website.com/regiter
and want to everything that does not have controller name (so will be category name) going to controller Category.
I can't work it out.
use
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'rules' => array(
'categoryName/<categoryName:\w+>' => array('site/category'),
'register' => array('site/register'),
'account' => array('site/account')
),
),
At first you must declare all rules for "non Category" actions, and after that dynamic rules (associated with category and antry):
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'rules' => array(
// for example if your account and register actions in user controller
// ... you can write
'account' => 'user/account',
'register' => 'user/register',
// or with one rule
'<action(account|register)>' => 'user/<action>',
// and for all other 'static actions', such as login, logout ...
// after yhat you can declire dynamic rules
'<categoryName:\w+>' => 'category/index',
'<categoryName:\w+>/<entryName:\w+>' => 'category/entry'
),
),
So the code Yii::app()->createUrl('user/register') will generate url website.com/register, and accordingly the url website.com/register "goes to" register action of user controller (all other static rules like this way).
Now dynamic rules: code
Yii::app()->createUrl('category/index', array(
'categoryName' => 'first-category-name'
))
will generate url website.com/first-category-name, and vice versa: the url website.com/first-category-name "goes to" category/index action and in it will be available $_GET['categoryName'] parameter, which will be equal to "second-category-name"․
Accordingly code
Yii::app()->createUrl('category/index', array(
'categoryName' => 'some-category-name',
'entryName' => 'some-entry-name'
))
will generate url website.com/some-category-name/some-entry-name, and in category/entry action you can get $_GET['categoryName'] equal to "some-category-name" and $_GET['entryName'] equal to some-entry-name.
I hope this help you to understand how works rules in Yii.
Thanks!

CakePHP empty field versus not empty field validations

I have the follow validation rule for a file:
modelFile.php
public $validate = array(
'image' => array(
'maxWidth' => array(
'rule' => array('maxWidth', 2000),
),
'maxHeight' => array(
'rule' => array('maxHeight', 2000),
),
'extension' => array(
'rule' => array('extension', array('gif', 'jpg', 'png', 'jpeg')),
),
'filesize' => array(
'rule' => array('filesize', 5120000),
)
)
);
Have a way to skip validations, if image are empty?
You may have to adjust how you check if the image is empty/not uploaded - I'm not sure if what I have is correct. But the idea is to check and unset the validation rule.
public function beforeValidate($options = array()) {
if (empty($this->data[$this->alias]['image']['name'])) {
unset($this->validate['image']);
}
return true;
}
See below URL
cakePHP optional validation for file upload
Or try it
"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
Ok, as far as I know there is no such code to set this in your $validate variable. So what you are going to have to do is:
In the beforeValidate of the corresponding model add the following piece of code:
<?php
# Check if the image is set. If not, unbind the validation rule
# Please note the answer of Abid Hussain below. He says the ['image'] will probably
# never be empty. So perhaps you should make use of a different way to check the variable
if (empty($this->data[$this->alias]['image'])){
unset($this->validate['image']);
}
I used http://bakery.cakephp.org/articles/kiger/2008/12/29/simple-way-to-unbind-validation-set-remaining-rules-to-required as my main article. But this function doesn't seem to be a default cake variable. The code above should work.

Change validation rules on the fly

I'm working on a form that contains user data, specifically a phone number field. The phone number typically isn't required so the only validation rule in the model is the usphone rule. However, if the user is submitting this form, the phone number becomes necessary. I thought I'd be able to simply add a validate rule on the fly, set the model and call the validates method, but either I'm doing it wrong or it's not working the way I expected.
In my controller:
# Update a few validation rules that are specific to this context
$this->Proposal->Requestor->validate['phone_number']['notempty'] = array(
'rule' => 'notEmpty',
'message' => 'Please enter a phone number so can can contact you with any questions about the work.',
'allowEmpty' => false,
'required' => true,
);
$validationErrors = array();
$this->Proposal->Requestor->set( $this->data['Requestor'] ); # $this->data['Requestor']['phone_number'] only (no other requestor data)
if( !$this->Proposal->Requestor->validates( array( 'fieldList' => array( 'phone_number' ) ) ) ) {
$validationErrors['Requestor'] = $this->Proposal->Requestor->validationErrors;
}
No errors are reported, even if I leave the phone number field empty. In this case, the only information I'm requesting from the user is their phone number, so the rest of the Requestor data is empty, but I've tried merging in the rest of the user data and I get the same result. If I remove the fieldList option, I get an error on a different field, but still nothing on the empty phone number.
Any idea what I'm missing here? I've been monkeying around with this for hours now and I just haven't found the right answer.
Thanks.
The solution ended up being twofold:
I had existing rule on the phone_number field that forced the value to be a US phone number. That rule also set allowEmpty to true and required to false. I wanted to catch an empty value so I could display a particularly precise message.
I had to update the existing rule to flip the allowEmpty and required values and also add a new rule with its last value set to true.
The final change, added in my controller action looks like this:
$this->Proposal->Requestor->validate = Set::merge(
$this->Proposal->Requestor->validate,
array(
'phone_number' => array(
'notempty' => array(
'rule' => 'notEmpty',
'message' => 'Please enter a phone number so can can contact you with any questions about the work.',
'allowEmpty' => false,
'required' => true,
'last' => true,
),
'usphone' => array(
'allowEmpty' => false,
'required' => true,
),
)
)
);
I can't remember whether I verified that the change to the existing usphone rule was strictly necessary given the last value of the new rule, but this combination is working fine.
You could try using the Multivalidatable Behaviour - http://bakery.cakephp.org/articles/dardosordi/2008/07/29/multivalidatablebehavior-using-many-validation-rulesets-per-model

AllowEmpty vs NotEmpty

New to CakePHP here - I'm going through the documentation on the site, trying to muster up some basic data validation for a model I'm creating. This will likely be the first of many questions I have about CakePHP.
In the CakePHP Book, the validation rules seem to specify two different methods for making sure that a field isn't empty - AllowEmpty, and NotEmpty.
Question - is there a tangible difference between these two? CakePHP states that validation rules should occur in your model or controller - is one better suited for a model, and the other for a controller? The Book doesn't say anything about this. I'm guessing that one is an older method that's simply still around?
What gives? Should I use a specific one, or both, or does it not matter?
Edit: I decided to check the CakePHP 1.3 class documentation for it (to check the default value of the allowEmpty attribute), but it doesn't even show up. It's not in the source code either...is there something I'm missing?
Welcome to Cake. I hope you enjoy it.
This is definitely one of the stranger aspects of Cake.
notEmpty is a rule in and of itself. You can define it in your $validation attribute. You can assign a message for when this validation fails. You can treat this as if it is any other validation rule.
allowEmpty is an option of another validation rule, normally not notEmpty. It is not a validation rule in-and-of-itself. This would allow, for example, you to define that a varchar field allows an empty string, '', or a string with no more than 20 characters.
Edit:
Here's some code
// model validation using 'notEmpty'
$validation = array(
'fieldName' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This value may not be left empty!'
),
... // other rules can go here
),
... // other fieldName can go here
);
// model validation using 'allowEmpty' to create an optional field
$validation = array(
'fieldName' => array(
'maxLength' => array(
'rule' => array('maxLength', 20),
'message' => 'This field may only contain 20 characters!',
'allowEmpty' => true // we'll also accept an empty string
),
... // other rules can go here
)
... // other fieldName can go here
);
I found a case where I had to use 'allowEmpty' => false instead of rule => 'notEmpty'. I had a form with an upload input (type='file') that had a validation rule of notEmpty, and it kept failing validation, even though the debugger showed the file[] array loaded. When I removed the 'notEmpty' rule and set allowEmpty => false, it worked, throwing an error when no file was chosen and accepting it when one was selected.
It must have something to do with the value being an array rather than a text value.
Its very simply to make server side validation in cakephp
Here is code for both validation (noEmpty, maxlength) for the same field.
'fieldName' => array(
'rule' => array('maxLength', 20),
'message' => 'fieldName should be less than 20 characters',
'allowEmpty' => true
),
'fieldName' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter field name',
),
),

CakePHP validation alpha problem w/ validation is checked - what am I doing wrong?

Excuse my ignorance on this question, but what seems to be an obvious fix is not coming together for me..
My validation is working perfectly fine with the exception of when I enter any alpha characters in my form field, I get a sql error:
SQL Error: 1054: Unknown column 'abcde' in 'where clause'...
As you can see I entered 'abcd' as a test..
But if I enter a numeric character and per my validation its all fine.. It appears the alpha value is being read as a column name??
Here is my validation rule:
...'Age' => array(
array(
'rule' => array('maxLength', 3),
array(
'rule' => 'numeric',
'allowEmpty' => true,
'message' => 'Age must be numeric.'
),
),
Here is my controller validation code:
if ($this->RequestHandler->isAjax()) {
if ($this->Plan->validates()) {
$this->Plan->set($this->data);
$errors = $this->Plan->invalidFields();
$this->set('errors', $errors);
} else {
$this->Plan->set($this->data);
}
}
As you can see I am returning my errors to my view, and the correct error "Age must be numeric." does in fact display as expected, but just with the SQL error stuff.
Thanks for any insight as to why this is happening.
Do you even read the manual? It's clearly stated in the CookBook that you need to give your rules names if you want to use multiple rules.
Also, your array is nested completely wrong. I don't know how this could be working, but anyway, this is how your validate should look like:
var $validate = array(
'Age' => array(
'length' => array(
'rule' => array('maxLength', 3)
),
'numbers' => array(
'rule' => 'numeric',
'allowEmpty' => true,
'message' => 'Age must be numeric.'
)
)
);

Categories