Custom validation rule in CakePHP not working as intended - php

I wrote a custom validation method inside my Submission model that basically allows a blank input field, but once someone enters something in it, it'll validate the data entered.
The validation inside my Submission Model looks like this (All other validation rules are working except for 'description'):
var $validate = array(
'title' => array(
'title' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a title'
),
'minLength' => array(
'rule' => array('minLength', 5),
'message' => 'Please make your title longer'
),
'maxLength' => array(
'rule' => array('maxLength', 300),
'message' => 'Your title needs to be shorter'
),
),
'description' => array(
'checkDescription' => array(
'rule' => array('validateDescription'),
'message' => 'Description must be greater than 5 characters'
),
),
'source' => array(
'source' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Enter a valid source URL'
),
'website' => array(
'rule' => 'url',
'message' => 'Please enter a valid source URL'
),
)
);
My method which is also in my Submission model (below the above code) is:
public function validateDescription($data) {
if(empty($data['Submission']['description']))
return true;
if((strlen($data['Submission']['description'])) <= 5)
return false;
}
I'm not sure why this isn't working at all. In my view, I've got this to display the error:
if ($form->isFieldError('Submission.description'))
echo ($form->error('Submission.description', null, array('class' => 'error')));
The only reason I'm trying to do this, is because using the normal validation with required => false and allowEmpty => true along with a minLength and maxLength validation rule weren't behaving how I intended.
Any help would be greatly appreciated! :)

The $data variable passed into the validation method only contains array($fieldname => $value). You're also not returning true for strings over length of 5. Your method should look like this:
public function validateDescription(array $data) {
$value = current($data);
return !$value || strlen($value) > 5;
}

Related

Validation "blank" or "empty" in cakephp Form

I just created a form in cakephp and I would like to do a validation for one of the field.
The form will only be submitted if this particular field is left empty.
Here's a my particular field
<?php echo
$this->Form->input('MyForm.fieldA', array(
'type' => 'text',
'label' => '',
'class' => 'span3 detector-form',
))
?>
And my validation code:
public $validate = array(
'fieldA' => array(
'rule' => 'blank',
'on' => 'submit',
'message' => 'Failed authorize',
'last' => true
),
);
P/s. I tried using
public $validate = array(
'fieldA' => array(
'rule' => 'blank',
'on' => 'create',
'message' => 'Failed authorize',
'last' => true
),
);
But the 'create' sounds like only worked when the field is created.So I changed to 'submit' for a testing purpose.
I tried to use rule''=> 'Empty' as well but the validation doesn't work. Or is there any other alternative rules that I can use to reach this goal?

Validating an ajax request with CakePHP ajax view returns all fields invalid always instead of the proper ones

I'm not sure why I keep receiving all the errors instead of just the invalid fields even when I fill out some of the required fields properly.
Submissions Controller:
public function submit() {
$this->set('title_for_layout', 'Submit - ');
if ($this->request->is('ajax')) {
if (!empty($this->request->data)) {
$this->Submission->set($this->request->data);
if ($this->Submission->invalidFields($this->request->data)) {
$formErrors = $this->Submission->validationErrors;
} else {
$formErrors = null;
}
} else {
$formErrors = null;
}
$this->set(compact('formErrors'));
}
/Submissions/json/submit.ctp:
<?php
$toReturn = array(
'formErrors' => $formErrors
);
echo json_encode($toReturn);
Submission model:
var $validate = array(
'title' => array(
'title' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a title'
),
'minLength' => array(
'rule' => array('minLength', 5),
'message' => 'Please make your title longer (e.g. IJL John F. Kennedy donated his presidential salary to charity)'
),
'maxLength' => array(
'rule' => array('maxLength', 300),
'message' => 'Your title needs to be shorter'
),
),
'description' => array(
'shortDescription' => array(
'rule' => array('shortDescription'),
'message' => 'Your description needs to be longer'
),
'longDescription' => array(
'rule' => array('longDescription'),
'message' => 'Your description needs to be shorter'
),
),
'source' => array(
'source' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Enter a valid source URL (e.g. http://en.wikipedia.org/wiki/Penguins)'
),
'website' => array(
'rule' => 'url',
'message' => 'Enter a valid source URL (e.g. http://en.wikipedia.org/wiki/Penguins)'
),
),
'category' => array(
'category' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please choose a category'
)
)
);
Form values that are getting serialized and sent:
Errors I'm getting in a json response:
Pulling hair out over here :|
You seem to have got a little muddle up with validates() and invalidFields()
invalidFields() returns the invalid fields after a validates(), see: http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html
So your code should look something like this:
$this->Submission->set($this->request->data);
if (!$this->Submission->validates()) {
$formErrors = $this->Submission->invalidFields();
} else {
$formErrors = null;
}
First, set the data to the model:
$this->ModelName->set($this->request->data);
Then, to check if the data validates, use the validates method of the model, which will return true if it validates and false if it doesn’t:
if ($this->ModelName->validates()) {
// it validated logic
} else {
// didn't validate logic
$errors = $this->ModelName->validationErrors;
}
Validating Data from the Controller

cakephp show validation errors with jquery

I'm using cakephp 2.0 and I'm having problem using Cake's validation thing, which works wonderful when used for it alone.
var $validate = array(
'loginname' => array(
'minCharactersRule' => array(
'rule' => array('minLength', 3),
'required' => true,
'allowEmpty' => false,
'on' => 'create',
),
'alphaNumericRule' => array(
'rule' => 'alphaNumeric',
),
'uniqueRule' => array(
'rule' => 'isUnique',
),
),
'password' => array(
'minCharactersRule' => array(
'rule' => array('minLength', 5),
'required' => true,
'allowEmpty' => false,
),
// on so on ...
Due to Internalization I put the error messages into the view like this:
echo $this->Form->input('display_name', array(
// some other options ...
'error' => array(
'betweenRule' => __('Your Dispay Name must contain at least 3 characters and should be maximal 20 characters long.'),
'uniqueRule' => __('This Display Name is already in use!'),
),
);
Now I want jQuery to validate the form on client-side as well with some little - sexy message box to return validation errors if something goes wrong.
The Ajax Request works fine but the problem here is: I only get returned the name of the validation rule, not the message.
sure: Because I didn't specified any messages in the model.
But how can I get those messages I declared in the view?
Is there any solution without having to type everything twice (PHP and JS)?

CakePHP why am I getting this error?

Here is the error message:
Warning (2): preg_match() [http://php.net/function.preg-match]: Delimiter must not be alphanumeric or backslash [CORE/cake/libs/model/model.php, line 2611]
This is happening when I call the following code from my controller:
$this->Account->save($this->data)
The model looks like this:
class Account extends AppModel
{
var $validate = array(
'first_name' => array(
'rule' => array('minLength', 1),
'required' => true
),
'last_name' => array(
'rule' => array('minLength', 1),
'required' => true
),
'password' => array(
'rule' => array('minLength', 8),
'required' => true
),
'email' => array(
'emailRule1' => array(
'rule' => 'email',
'required' => true,
'message' => 'You must specify a valid email address'
),
'emailRule2' => array(
'rule' => 'unique',
'message' => 'That email address is already in our system'
)
)
);
}
I found a similar problem explained here
He solved it by changing required' => true to required' => array(true) I tried that for every occurange in my model but it did not fix the problem.
The problem was I named the rule unique it should be isUnique instead.
I would have figured this out much faster with a better error message.

CakePHP multirule validation

I am trying to get multiple rules to run during an upload validation. One validation is built in and one is custom. The custom one works fine however the built in one is not working. The custom one extension was working on another field earlier just fine. Do I have this setup correct?
var $validate = array(
'description' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'required' => true
),
'title' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'required' => true
),
'Filedata' => array(
'rule' => array('FileExtCheck'),
'message' => 'Please supply a valid type.',
'required' => true
),
'Thumbdata' => array(
'dimensions'=>array(
'rule' => array('dimensions','120','142'),
'message' => 'Your image dimensions are incorrect: 120x142'
),
'extension' => array(
'rule' => array('extension'=>array('jpg','jpeg','png')),
'message' => 'Please supply a valid type.',
'required'=>true
)
)
);
The one I am having issue with is Thumbdata. I want the Thumbdata field to be required and make sure it has correct dimensions and is an image of jpg, jpeg or png. I don't want animated gif's.
I guess, you have a syntax error - unnecessary =>. Should be:
'rule' => array('extension', array('jpg','jpeg','png')),

Categories