Wednesday, March 9, 2022

[FIXED] Validation rules notEmpty and requirePresence

Issue

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.


Solution

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.



Answered By - ndm

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.