Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - validation can be empty but if not empty need to be at least 4 character & numeric

Tags:

cakephp

How can I create a validation rule that allows a field to be empty but if it is not, it needs to be numeric and 4 character long?

This is what I have now

'year' => array(
        'numeric' => array(
            'rule' => 'numeric',
            'message' => 'Numbers only'
        ),
        'maxLength' => array(
            'rule' => array('maxLength', 4),
            'message' => 'Year in YYYY format'
        ),
        'minLength' => array(
            'rule' => array('minLength', 4),
            'message' => 'Year in YYYY format'
        )
    )

That works great but when the field is empty, it still run the validation.

Thanks,
Tee

like image 741
teepusink Avatar asked May 06 '11 15:05

teepusink


2 Answers

The following snippet should do the trick:

'numeric' => array(
    'rule' => 'numeric',
    'allowEmpty' => true,
    'message' => 'Numbers only'
),

See also the chapter about data validation in the cookbook.

like image 138
dhofstet Avatar answered Oct 12 '22 12:10

dhofstet


you also forgot the last => true paramater - see http://www.dereuromark.de/2010/07/19/extended-core-validation-rules/ for details

like image 34
mark Avatar answered Oct 12 '22 11:10

mark