David Yell
David Yell

Reputation: 11855

Validation rules notEmpty and requirePresence

I would like to know how the various validation rules interact with one another and how they layer up.

I think the easiest way is with a few examples.

Let's assume we are submitting a Post for a blog. So we'll work on the validation in our PostsTable.

->notEmpty('title')
->requirePresence('title')
->add('title', 'length', [
    'rule' => ['minLength', 5],
    'message' => 'Must be longer than 5 characers'
]);

->notEmpty('download_speed')
->add('download_speed', 'rule', ['rule' => 'numeric'])
->requirePresence('download_speed')

So in this example, are the notEmpty() and requirePresence() rules actually needed, because the minLength will enforce the presence and not empty because obviously an empty string is less than 5 characters?

Similarly in the second example, an empty value will not be numeric so that rule would in turn force it's presence.

Upvotes: 3

Views: 3359

Answers (2)

Ruben Mercado
Ruben Mercado

Reputation: 1

// Check:  != ''
    ->notEmpty('title')

// Check:  isset()
    ->requirePresence('title')

// Check:  5 characters at least but can be white spaces 
    ->add('title', 'length', [
         'rule' => ['minLength', 5],
          'message' => 'Must be at least 5 characters in length'
     ]);

// Check:  5 characters without white spaces behind or after
     ->add('title', 'custom', [
         'rule' => function ($currentData) {                        
              $realLenght = strlen(trim($currentData));  
               if ($realLenght >= 5 ) {return true;}
               return false;                  
          },                                    
         'message' => 'Must be at least 5 characters in length. Avoid unnecessary white spaces''
    ]);

Upvotes: 0

ndm
ndm

Reputation: 60463

requirePresence is the only built-in rule that is being triggered when the given field doesn't exist, all other rules are only being applied in case the field is actually present, ie minLength will not trigger in case the title field doesn't exist. So if you need a field to be present and thus validated, then you'll need the requirePresence rule.

Also minLength will be satisfied by whitespaces, so if you don't consider 5 whitespaces a valid title, then you also cannot ditch the notEmpty rule (though you might want to exchange both, notEmpty and minLength for a custom rule instead that trims the title first, so that 4 whitespaces followed by a char don't make it past the validation, alternatively you could trim the data in your entity).

The only rule that might not be needed in your example is the notEmpty rule for the download_speed field, because, as you already figured, an empty value isn't a valid number.

Upvotes: 4

Related Questions