开发者

Custom validation rule in CakePHP not working as intended

开发者 https://www.devze.com 2023-04-12 21:03 出处:网络
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.

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'),
     开发者_Python百科       '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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号