ice framework documentation ice doc v1.10.1
  1. namespace Ice\Validation\Validator;
  2.  
  3. use Ice\Exception;
  4. use Ice\Validation;
  5. use Ice\Validation\Validator;
  6.  
  7. /**
  8. * NotIn validator.
  9. *
  10. * @package Ice/Validation
  11. * @category Security
  12. * @author Ice Team
  13. * @copyright (c) 2014-2023 Ice Team
  14. * @license http://iceframework.org/license
  15. *
  16. *
  17.  *  $validation = new Ice\Validation();
  18.  *
  19.  *  $validation->rules([
  20.  *      'status' => 'notIn:unactive,removed',
  21.  *      'username' => [
  22.  *          'notIn' => [
  23.  *              'values' => ['about', 'admin', 'user', 'root'],
  24.  *              'message' => 'Field :field is reserved',
  25.  *              'label' => 'Nick'
  26.  *          ],
  27.  *      ]
  28.  *  ]);
  29.  *
  30.  *  $valid = $validation->validate($_POST);
  31.  *
  32.  *  if (!$valid) {
  33.  *      $messages = $validation->getMessages();
  34.  *  }
  35.  * 
  36. */
  37. class NotIn extends Validator
  38. {
  39. /**
  40. * Validate the validator
  41. * Options: values (0,1,2..), label, message
  42. *
  43. * @param Validation validation
  44. * @param string field
  45. * @return boolean
  46. */
  47. public function validate( validation, string! field) -> boolean
  48. {
  49. var value, label, message, i18n, replace, values;
  50. let value = validation->getValue(field);
  51. if value === "" || value === null {
  52. return true;
  53. }
  54. let values = this->getOptions(Validator::NUMERIC);
  55. if empty values {
  56. let values = this->get("values");
  57. }
  58. if typeof values != "array" {
  59. throw new Exception("Values must be an array");
  60. }
  61. if in_array(value, values) {
  62. if this->has("label") {
  63. let label = this->get("label");
  64. } else {
  65. let label = validation->getLabel(field);
  66. }
  67. if this->has("message") {
  68. let message = this->get("message");
  69. } else {
  70. let message = validation->getDefaultMessage("notIn");
  71. }
  72. // Translate strings
  73. if validation->getTranslate() === true && validation->getDi()->has("i18n") {
  74. let i18n = validation->getDi()->get("i18n"),
  75. label = i18n->translate(label),
  76. message = i18n->translate(message);
  77. }
  78. let replace = [":field": label, ":values": join(", ", values)];
  79. validation->addMessage(field, strtr(message, replace));
  80. return false;
  81. }
  82. return true;
  83. }
  84. }