PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 9, 2022

[FIXED] Validation rules notEmpty and requirePresence

 March 09, 2022     cakephp-3.0     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing