Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AllowEmpty vs NotEmpty

New to CakePHP here - I'm going through the documentation on the site, trying to muster up some basic data validation for a model I'm creating. This will likely be the first of many questions I have about CakePHP.

In the CakePHP Book, the validation rules seem to specify two different methods for making sure that a field isn't empty - AllowEmpty, and NotEmpty.

Question - is there a tangible difference between these two? CakePHP states that validation rules should occur in your model or controller - is one better suited for a model, and the other for a controller? The Book doesn't say anything about this. I'm guessing that one is an older method that's simply still around?

What gives? Should I use a specific one, or both, or does it not matter?

Edit: I decided to check the CakePHP 1.3 class documentation for it (to check the default value of the allowEmpty attribute), but it doesn't even show up. It's not in the source code either...is there something I'm missing?

like image 980
jedd.ahyoung Avatar asked Jul 01 '11 22:07

jedd.ahyoung


1 Answers

Welcome to Cake. I hope you enjoy it.

This is definitely one of the stranger aspects of Cake.

notEmpty is a rule in and of itself. You can define it in your $validation attribute. You can assign a message for when this validation fails. You can treat this as if it is any other validation rule.

allowEmpty is an option of another validation rule, normally not notEmpty. It is not a validation rule in-and-of-itself. This would allow, for example, you to define that a varchar field allows an empty string, '', or a string with no more than 20 characters.

Edit:

Here's some code

// model validation using 'notEmpty'
$validation = array(
    'fieldName' => array(
        'notEmpty' => array(
            'rule' => 'notEmpty',
            'message' => 'This value may not be left empty!'
        ),
        ... // other rules can go here
    ),
    ... // other fieldName can go here
);


// model validation using 'allowEmpty' to create an optional field
$validation = array(
    'fieldName' => array(
        'maxLength' => array(
             'rule' => array('maxLength', 20),
             'message' => 'This field may only contain 20 characters!',
             'allowEmpty' => true    // we'll also accept an empty string
        ), 
        ... // other rules can go here
    )
    ... // other fieldName can go here
);
like image 156
Charles Sprayberry Avatar answered Sep 17 '22 20:09

Charles Sprayberry