Skip to content

Commit

Permalink
Merge pull request #284 from tobiashinz/listContains
Browse files Browse the repository at this point in the history
List contains
  • Loading branch information
willemwollebrants committed Aug 21, 2019
2 parents 89117a9 + f87d5b1 commit 76e4418
Show file tree
Hide file tree
Showing 32 changed files with 105 additions and 8 deletions.
31 changes: 24 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ V::lang('ar');
* `lengthMax` - String must be less than given length
* `min` - Minimum
* `max` - Maximum
* `listContains` - Performs in_array check on given array values (the other way round than `in`)
* `in` - Performs in_array check on given array values
* `notIn` - Negation of `in` rule (not in array of values)
* `ip` - Valid IP address
Expand Down Expand Up @@ -443,6 +444,23 @@ $v->rules([
$v->validate();
```

## listContains fields usage
The `listContains` rule checks that the field is present in a given array of values.
```php
$v->rule('listContains', 'color', 'yellow');
```

Alternate syntax.
```php
$v = new Valitron\Validator(['color' => ['blue', 'green', 'red', 'yellow']]);
$v->rules([
'listContains' => [
['color', 'yellow']
]
]);
$v->validate();
```

## in fields usage
The `in` rule checks that the field is present in a given array of values.
```php
Expand Down Expand Up @@ -970,7 +988,7 @@ Valitron\Validator::addRule('alwaysFail', function($field, $value, array $params
```

You can also use one-off rules that are only valid for the specified
fields.
fields.

```php
$v = new Valitron\Validator(array("foo" => "bar"));
Expand All @@ -982,12 +1000,12 @@ $v->rule(function($field, $value, $params, $fields) {
This is useful because such rules can have access to variables
defined in the scope where the `Validator` lives. The Closure's
signature is identical to `Validator::addRule` callback's
signature.
signature.

If you wish to add your own rules that are not static (i.e.,
your rule is not static and available to call `Validator`
instances), you need to use `Validator::addInstanceRule`.
This rule will take the same parameters as
your rule is not static and available to call `Validator`
instances), you need to use `Validator::addInstanceRule`.
This rule will take the same parameters as
`Validator::addRule` but it has to be called on a `Validator`
instance.

Expand Down Expand Up @@ -1067,7 +1085,7 @@ You can also add rules on a per-field basis:
$rules = [
'required',
['lengthMin', 4]
];
];

$v = new Valitron\Validator(array('foo' => 'bar'));
$v->mapFieldRules('foo', $rules);
Expand Down Expand Up @@ -1155,4 +1173,3 @@ before running the tests:
6. Push to the branch (`git push origin my-new-feature`)
7. Create new Pull Request
8. Pat yourself on the back for being so awesome

1 change: 1 addition & 0 deletions lang/ar.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
'min' => "يجب ان يكون اعلي من %s",
'max' => "يجب ان يكون اقل من %s",
'in' => "الُمدخل يغير صحيح",
'listContains' => "الُمدخل يغير صحيح",
'notIn' => "الُمدخل يغير صحيح",
'ip' => "رقم الإتصال غير صحيح",
'email' => "البريد الألكتروني غير صحيح",
Expand Down
1 change: 1 addition & 0 deletions lang/az.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "%d qədər uzunluğu olmalıdır",
'min' => "minimum %s qədər olmalıdır",
'max' => "maksimum %s qədər olmalıdır",
'listContains' => "yalnış dəyər ehtiva edir",
'in' => "yalnış dəyər ehtiva edir",
'notIn' => "yalnış dəyər ehtiva edir",
'ip' => "düzgün IP ünvanı deyil",
Expand Down
1 change: 1 addition & 0 deletions lang/bg.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "трябва да бъде %d символа дълго",
'min' => "трябвя да бъде поне %s",
'max' => "трябва да бъде не повече от %s",
'listContains' => "съдържа невалидна стойност",
'in' => "съдържа невалидна стойност",
'notIn' => "съдържа невалидна стойност",
'ip' => "е невалиден IP адрес",
Expand Down
1 change: 1 addition & 0 deletions lang/de.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "kann nicht länger als %d sein",
'min' => "muss größer als %s sein",
'max' => "muss kleiner als %s sein",
'listContains' => "enthält einen ungültigen Wert",
'in' => "enthält einen ungültigen Wert",
'notIn' => "enthält einen ungültigen Wert",
'ip' => "enthält keine gültige IP-Addresse",
Expand Down
1 change: 1 addition & 0 deletions lang/el.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "πρέπει να είναι μεγαλύτερο από %d",
'min' => "πρέπει να είναι τουλάχιστον %s",
'max' => "δεν πρέπει να είναι περισσότερο από %s",
'listContains' => "περιέχει μη έγκυρη τιμή",
'in' => "περιέχει μη έγκυρη τιμή",
'notIn' => "περιέχει μη έγκυρη τιμή",
'ip' => "δεν είναι έγκυρη διεύθυνση IP",
Expand Down
1 change: 1 addition & 0 deletions lang/en.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "must be %d characters long",
'min' => "must be at least %s",
'max' => "must be no more than %s",
'listContains' => "contains invalid value",
'in' => "contains invalid value",
'notIn' => "contains invalid value",
'ip' => "is not a valid IP address",
Expand Down
1 change: 1 addition & 0 deletions lang/fi.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "on lyhyempi kuin %d",
'min' => "ei ole vähintään %s",
'max' => "ei ole enintään %s",
'listContains' => "sisältää virheellisen arvon",
'in' => "sisältää virheellisen arvon",
'notIn' => "sisältää virheellisen arvon",
'ip' => "ei ole oikeanmuotoinen IP-osoite",
Expand Down
1 change: 1 addition & 0 deletions lang/fr.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "doit être plus long que %d",
'min' => "doit être plus grand que %s",
'max' => "doit être plus petit que %s",
'listContains' => "contient une valeur non valide",
'in' => "contient une valeur non valide",
'notIn' => "contient une valeur non valide",
'ip' => "n'est pas une adresse IP valide",
Expand Down
1 change: 1 addition & 0 deletions lang/id.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "harus lebih panjang dari %d",
'min' => "harus lebih besar dari %s",
'max' => "harus kurang dari %s",
'listContains' => "berisi nilai/value yang tidak valid",
'in' => "berisi nilai/value yang tidak valid",
'notIn' => "berisi nilai/value yang tidak valid",
'ip' => "format alamat IP tidak benar",
Expand Down
1 change: 1 addition & 0 deletions lang/it.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "deve avere una lunghezza di %d",
'min' => "deve essere superiore a %s",
'max' => "deve essere inferiore a %s",
'listContains' => "contiene un valore non valido",
'in' => "contiene un valore non valido",
'notIn' => "contiene un valore non valido",
'ip' => "non è un indirizzo IP valido",
Expand Down
1 change: 1 addition & 0 deletions lang/ja.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "は%d文字で入力してください",
'min' => "には%sより大きな値を入力してください",
'max' => "には%sより小さな値を入力してください",
'listContains' => "には選択できない値が含まれています",
'in' => "には選択できない値が含まれています",
'notIn' => "には選択できない値が含まれています",
'ip' => "はIPアドレスの書式として正しくありません",
Expand Down
1 change: 1 addition & 0 deletions lang/ko.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "의 길이는 %d 이어야 합니다.",
'min' => "은(는) %s 이상이어야 합니다.",
'max' => "은(는) %s 이하여야 합니다.",
'listContains' => "은(는) 올바르지 않은 값을 포함하고 있습니다.",
'in' => "은(는) 올바르지 않은 값을 포함하고 있습니다.",
'notIn' => "은(는) 올바르지 않은 값을 포함하고 있습니다.",
'ip' => "은(는) 올바르지 않은 IP입니다.",
Expand Down
1 change: 1 addition & 0 deletions lang/lt.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
'length' => "turi būti %d ženklų ilgio",
'min' => "turi būti bent %s",
'max' => "turi būti ne daugiau kaip %s",
'listContains' => "turi neteisingą vertę",
'in' => "turi neteisingą vertę",
'notIn' => "turi neteisingą vertę",
'ip' => "nėra teisingas IP adresas",
Expand Down
1 change: 1 addition & 0 deletions lang/lv.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "nedrīkst būt garāks par %d simboliem",
'min' => "jābūt garākam par %s simboliem",
'max' => "jābūt īsākam par %s simboliem",
'listContains' => "lauks satur nederīgu vērtību",
'in' => "lauks satur nederīgu vērtību",
'notIn' => "lauks satur nederīgu vērtību",
'ip' => " lauks nav derīga IP adrese",
Expand Down
1 change: 1 addition & 0 deletions lang/nb.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "må være %d tegn langt",
'min' => "må være minst %s",
'max' => "må ikke være mer enn %s",
'listContains' => "inneholder ugyldig verdi",
'in' => "inneholder ugyldig verdi",
'notIn' => "inneholder ugyldig verdi",
'ip' => "er ikke en gyldig IP adresse",
Expand Down
1 change: 1 addition & 0 deletions lang/nl.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "moet minstens %d karakters lang zijn",
'min' => "moet minstens %s zijn",
'max' => "mag niet meer zijn dan %s",
'listContains' => "bevat een ongeldige waarde",
'in' => "bevat een ongeldige waarde",
'notIn' => "bevat een ongeldige waarde",
'ip' => "is geen geldig IP-adres",
Expand Down
1 change: 1 addition & 0 deletions lang/nn.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "må være %d tegn",
'min' => "må være minst %s",
'max' => "må ikke være mer enn %s",
'listContains' => "inneholder ugyldig verdi",
'in' => "inneholder ugyldig verdi",
'notIn' => "inneholder ugyldig verdi",
'ip' => "er ikkje ein gyldig IP Adresse",
Expand Down
1 change: 1 addition & 0 deletions lang/pl.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "musi być dłuższe niż %d",
'min' => "musi być przynajmniej %s",
'max' => "nie może być większe niż %s",
'listContains' => "zawiera nieprawidłową wartość",
'in' => "zawiera nieprawidłową wartość",
'notIn' => "zawiera nieprawidłową wartość",
'ip' => "nie jest prawidłowym adresem IP",
Expand Down
2 changes: 1 addition & 1 deletion lang/pt-br.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@
'containsUnique' => "deve conter apenas valores únicos",
'subset' => "contém um item que não está na lista",
'arrayHasKeys' => "não contém todas as chaves requeridas"
);
);
1 change: 1 addition & 0 deletions lang/ro.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "trebuie sa fie mai lung decat %d",
'min' => "trebuie sa fie cel putin %s",
'max' => "nu trebuie sa fie mai mult de %s",
'listContains' => "contine caractere invalide",
'in' => "contine caractere invalide",
'notIn' => "contine o valoare invalida",
'ip' => "nu este o adresa IP valida",
Expand Down
1 change: 1 addition & 0 deletions lang/ru.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "должно быть длиннее, чем %d",
'min' => "должно быть не менее, чем %s",
'max' => "должно быть не более, чем %s",
'listContains' => "содержит неверное значение",
'in' => "содержит неверное значение",
'notIn' => "содержит неверное значение",
'ip' => "не является валидным IP адресом",
Expand Down
1 change: 1 addition & 0 deletions lang/sk.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "musí byť dlhý aspoň %d",
'min' => "musí byť dlhý minimálne %s",
'max' => "musí byť maximálne %s",
'listContains' => "obsahuje nepovolenú hodnotu",
'in' => "obsahuje nepovolenú hodnotu",
'notIn' => "obsahuje nepovolenú hodnotu",
'ip' => "nie je korektná IP adresa",
Expand Down
1 change: 1 addition & 0 deletions lang/sv.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "måste vara %d tecken långt",
'min' => "måste vara minst %s",
'max' => "får inte vara mer än %s",
'listContains' => "innehåller ogiltigt värde",
'in' => "innehåller ogiltigt värde",
'notIn' => "innehåller ogiltigt värde",
'ip' => "är inte en giltlig IP-adress",
Expand Down
1 change: 1 addition & 0 deletions lang/th.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "ต้องมีความยาวมากกว่า %d",
'min' => "ต้องมีอย่างน้อย %s",
'max' => "ต้องไม่มากเกิน %s",
'listContains' => "ประกอบด้วยค่าที่ไม่ถูกต้อง",
'in' => "ประกอบด้วยค่าที่ไม่ถูกต้อง",
'notIn' => "ประกอบด้วยค่าที่ไม่ถูกต้อง",
'ip' => "ไม่ใช่ IP ที่ถูกต้อง",
Expand Down
1 change: 1 addition & 0 deletions lang/tr.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "en az %d adet uzunluğunda olmalı",
'min' => "en az böyle olmalı %s",
'max' => "bundan daha fazla olmalı %s",
'listContains' => "geçersiz değer içeriyor",
'in' => "geçersiz değer içeriyor",
'notIn' => "geçersiz değer içeriyor",
'ip' => "geçerli bir IP adresi değil",
Expand Down
1 change: 1 addition & 0 deletions lang/uk.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "має бути довшим, ніж %d",
'min' => "має бути більше, ніж %s",
'max' => "повинно бути менше, ніж %s",
'listContains' => "містить невірне значення",
'in' => "містить невірне значення",
'notIn' => "містить невірне значення",
'ip' => "не є валідною IP адресою",
Expand Down
1 change: 1 addition & 0 deletions lang/vi.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "phải dài hơn %d",
'min' => "ít nhất %s",
'max' => "tối đa %s",
'listContains' => "chứa giá trị không hợp lệ",
'in' => "chứa giá trị không hợp lệ",
'notIn' => "chứa giá trị không hợp lệ",
'ip' => "địa chỉ IP không hợp lệ",
Expand Down
1 change: 1 addition & 0 deletions lang/zh-cn.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "长度必须大于 %d",
'min' => "必须大于 %s",
'max' => "必须小于 %s",
'listContains' => "无效的值",
'in' => "无效的值",
'notIn' => "无效的值",
'ip' => "无效IP地址",
Expand Down
1 change: 1 addition & 0 deletions lang/zh-tw.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'length' => "長度必須大於 %d",
'min' => "必須大於 %s",
'max' => "必須小於 %s",
'listContains' => "無效的值",
'in' => "無效的值",
'notIn' => "無效的值",
'ip' => "無效IP地址",
Expand Down
23 changes: 23 additions & 0 deletions src/Valitron/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,29 @@ protected function validateIn($field, $value, $params)
return in_array($value, $params[0], $strict);
}

/**
* Validate a field is contained within a list of values
*
* @param string $field
* @param mixed $value
* @param array $params
* @return bool
*/
protected function validateListContains($field, $value, $params)
{
$isAssoc = array_values($value) !== $value;
if ($isAssoc) {
$value = array_keys($value);
}

$strict = false;
if (isset($params[1])) {
$strict = $params[1];
}

return in_array($params[0], $value, $strict);
}

/**
* Validate a field is not contained within a list of values
*
Expand Down
29 changes: 29 additions & 0 deletions tests/Valitron/ValidateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,35 @@ public function testBetweenInvalidRange()
$this->assertFalse($v->validate());
}

public function testListContainsValid()
{
$v = new Validator(array('color' => array('blue', 'green', 'red', 'yellow')));
$v->rule('listContains', 'color', 'red');
$this->assertTrue($v->validate());
}

public function testListContainsValidAltSyntax()
{
$v = new Validator(array('color' => array('blue', 'green', 'red')));
$v->rules(array(
'listContains' => array(
array('color', 'red')
)
));
$this->assertTrue($v->validate());
}

public function testListContainsInvalidAltSyntax()
{
$v = new Validator(array('color' => array('blue', 'green', 'red')));
$v->rules(array(
'listContains' => array(
array('color', 'yellow')
)
));
$this->assertFalse($v->validate());
}

public function testInValid()
{
$v = new Validator(array('color' => 'green'));
Expand Down

0 comments on commit 76e4418

Please sign in to comment.