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,
TeeThe 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,})?$\/"
)
)
);
精彩评论