开发者

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

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

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


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.


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


The 'last' attribute should go => to false. So the final solution should look like:

'year' => array(  
    'numeric' => array(  
    'rule' => 'numeric',  
    'allowEmpty' => true,  
    'message' => 'Numbers only'  
    'last' => false   ), ...

I personally like to separate things (more readability and easier in debugging):

'year' => array(  
    'allowEmpty' => array(  
    'allowEmpty'=>true,  
    'last'=>false   ),   'numeric'=> array(  
    'rule' =>'numeric',  
    'message' => 'Numbers only'  
),...   )


'numeric' => array(
    'rule' => 'numeric',
    'message' => 'Numbers only'
),
'maxLength' => array(
    'rule' => array('maxLength', 10),
    'message' => '10 digit no'
)


There is a way to do this simply

    array(
        'myfield' => array(
            "rule_empty" => array(
                    'rule' =>  '#.*#i',  // validate everything
                    'allowEmpty' => true,
                    'last' => false
                ),
            "rule_price" => array(
                'message' => 'Is not a valid price ! ',
                'rule' => "\/^[0-9]+(?:(\\.|,)[0-9]{1,})?$\/"
            )
        )
    );
0

精彩评论

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