Advertisement
tilz0R

Valitron validate() fixed

Nov 24th, 2015
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.24 KB | None | 0 0
  1. /****************************/
  2. /*        ABOUT PATCH       */
  3. /****************************/
  4. /*
  5. In my application, I have a situation, where user can update some records in database.
  6. Records which are passed as data array are updated only, so I need to validate them first.
  7.  
  8. If I use 'required' on all fields possible, then I must provide all fields on update,
  9. so I removed 'required' parameter and only include necessary rules.
  10.  
  11. What I want to get, for example:
  12. If I want to edit 'element_name' field, then it MUST be at least 'minLength' value 1, but with
  13. current version, if 'element_name' is passed empty, validate() function ignores it as
  14. says it is successfully validated which is NOT TRUE. 'element_name' is not min length 1, because it is empty!
  15.  
  16. Another case would be for 'element_quantity'. IF IT IS PASSED (not need to be), then it HAS TO BE an integer value.
  17. Again, if I pass empty value, this is NOT an integer and if there was no 'required' field, field was ignored and
  18. flagged as successfully validated.
  19.  
  20. */
  21.  
  22. /****************************/
  23. /*         EXAMPLE 1        */
  24. /****************************/
  25. //Input data
  26. $data = [
  27.     'element_name' => '' //Empty name, min lenght is NOT 1
  28.     'element_quantity' => '' //Empty value, NOT and integer
  29. ];
  30.  
  31. //Rules
  32. $v->rule('lengthMin', 'element_name', 1)->message(__('Name cannot be empty!'))
  33.   ->rule('integer', 'element_quantity')->message(__('Quantity must be integer!'));
  34.  
  35. //Before PATCH
  36. //Validation passed, 'required' options is not set, values are empty and validation ignores them! False!
  37.  
  38. //After PATCH
  39. //Validation failed, because 'element_name' is not at least 1 character long and 'element_quantity' is NOT an integer
  40.  
  41. /****************************/
  42. /*         EXAMPLE 2        */
  43. /****************************/
  44. //Input data
  45. $data = [
  46.     'element_name' => '' //Empty name, min lenght is NOT 1
  47. ];
  48.  
  49. //Rules in all cases
  50. $v->rule('lengthMin', 'element_name', 1)->message(__('Name cannot be empty!'))
  51.   ->rule('integer', 'element_quantity')->message(__('Quantity must be integer!'));
  52.  
  53. //Before
  54. //Validation passed, 'element_name' doesn't have 'required' field set
  55.  
  56. //After
  57. //Validation failed, 'element_name' must be at least 1 character long, IF EXISTS IN DATA ARRAY.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement