Compare commits

...

51 Commits

Author SHA1 Message Date
Willem Wollebrants
fadce39f5f
Merge pull request #365 from blueyestar/master
added missing translation for zh-cn and zh-tw
2022-10-14 13:54:24 +02:00
Willem Wollebrants
5659b0a942
Merge pull request #364 from metakin/fix-typo
typo fix
2022-10-14 13:53:54 +02:00
Willem Wollebrants
fdc64d193a
Merge pull request #359 from mehdihasanpour/add-persian
add persian language
2022-10-14 13:52:39 +02:00
Willem Wollebrants
0cbc5834b0
Merge pull request #350 from eugene-borovov/requirewith-dot-notation
Added dot notation to requireWith(out)
2022-10-14 13:52:03 +02:00
Justin Li
1b86b4f454 added missing translation for zh-cn and zh-tw 2022-10-11 11:56:38 -04:00
metakin
fbb596d220 typo fix 2022-10-11 03:22:02 +03:00
Willem Wollebrants
57a9f68f22
Merge pull request #363 from Tautve/issue_357
Fixed Issue #357
2022-10-03 09:50:30 +02:00
tautvydaskarvelis
fd902d1def Issue #357 2022-10-01 10:06:52 +03:00
mehdi hasanpour
ac960d625f add persian language 2022-07-02 15:59:33 +04:30
Willem Wollebrants
d0fb8ee84c
Merge pull request #354 from aldinhro/patch-1
Update sv.php
2022-03-16 10:16:07 +01:00
Aldin Hro
94c97e3e8e
Update sv.php
Added correct translations
2022-03-16 10:10:25 +01:00
Willem Wollebrants
9bf11f4374
Merge pull request #351 from hiroy/add-japanese-messages
Add Japanese messages for some rules
2021-12-07 09:05:12 +01:00
Hiroyuki Yamaoka
b619ef16ba Add Japanese messages for some rules 2021-12-07 14:18:08 +09:00
Eugene Borovov
b4e0d07495 Added dot notation to requireWith(out) 2021-11-21 01:55:32 +07:00
Willem Wollebrants
5ebd5d7af8
Merge pull request #344 from vlucas/issue-326
Test against PHP 8
2021-07-08 18:18:03 +02:00
Willem Wollebrants
f189549d2d make tests compatible with phpunit for php8 2021-07-07 11:55:52 +02:00
Willem Wollebrants
fe2ca630fb make tests compatible with phpunit for php8 2021-07-07 11:52:59 +02:00
Willem Wollebrants
035eca3093 make tests compatible with phpunit for php8 2021-07-07 11:47:59 +02:00
Willem Wollebrants
da91bdea70 make tests compatible with phpunit for php8 2021-07-07 11:44:08 +02:00
Willem Wollebrants
ba90097aa5
Merge pull request #343 from vlucas/issue-332
detect numeric array when keys are out of order , fixes #332
2021-07-06 14:22:56 +02:00
Willem Wollebrants
d12a77deed check first (#332) 2021-07-06 14:16:59 +02:00
Willem Wollebrants
be8cb9e074 add parameter to force in and listContains to look at array keys 2021-07-06 10:58:22 +02:00
Willem Wollebrants
500472808c detect numeric array when keys are out of order (#332) 2021-07-05 22:14:24 +02:00
Willem Wollebrants
567fbb9965
Merge pull request #340 from euantorano/patch-1
Update build status badge
2021-07-05 18:42:08 +02:00
Willem Wollebrants
ae5a778541
Merge pull request #342 from vlucas/issue-328
Correct label for 'length' in zh-cn (#328)
2021-07-05 18:41:34 +02:00
Willem Wollebrants
1c0674c23f Correct label for 'length' in zh-cn (#328) 2021-07-05 18:40:18 +02:00
Willem Wollebrants
4c7d0070dd
Merge pull request #341 from vlucas/issue-335
add missing assertion to testNotInInvalidAltSyntax (#335)
2021-07-05 18:34:54 +02:00
Willem Wollebrants
33148fa4ed add missing assertion to testNotInInvalidAltSyntax (#335) 2021-07-05 18:33:50 +02:00
Euan Torano
f0c48c4adf
Update build status badge
As GitHub Actions now runs CI, the build status badge must be from GitHub Actions.
2021-07-05 17:29:12 +01:00
Willem Wollebrants
0282ca420b
Merge pull request #338 from euantorano/feature/github-actions
Fixed #337 - add GitHub Actions workflow to run tests
2021-07-05 18:25:56 +02:00
Euan Torano
5deb47049a Added GitHub workflow file, removed Travis CI file. Changed how email DNS validation works to only check MX record. 2021-06-17 13:01:49 +01:00
Vance Lucas
f7e662e3c0
Merge pull request #334 from joebordes/sonarqube
merge IF statement with enclosing one (sonarqube static analysis)
2021-05-12 14:47:47 -05:00
joebordes
6b3c5ae608 merge IF statement with enclosing one (sonarqube static analysis) 2021-05-12 21:21:46 +02:00
Willem Wollebrants
81515dcc95
Merge pull request #325 from TomOudeRengerink/disable-auto-prepend-field-label
Allow disabling of auto prepending the field labels.
2020-12-01 12:14:45 +01:00
Tom Oude Rengerink
9f29a1b99a Added test for prepending field labels 2020-10-26 12:45:34 +01:00
Tom Oude Rengerink
bfa24585de Changed method name for readability and writting some docs. 2020-10-23 16:29:08 +02:00
Tom Oude Rengerink
6a6810e25c Removed some PHP Doc blocks generated by IDEA 2020-10-23 16:16:25 +02:00
Tom Oude Rengerink
128097ea16 Allow disabling of auto prepending the field labels shown in the error message. 2020-10-23 16:11:20 +02:00
Willem Wollebrants
9268adeeb4
Merge pull request #316 from euantorano/patch-1
Fix invalid opening bracket for arrayHasKeys example
2020-07-10 10:55:05 +02:00
Euan
a204228146
Fix mismatched open array for arrayHasKeys. 2020-07-07 16:08:30 +01:00
Willem Wollebrants
4af076d19f
Merge pull request #312 from PowerPan/sl
Add SL
2020-05-14 16:50:07 +02:00
Johannes Rudolph
3d2b0ef5f7 Add SL 2020-05-04 13:34:58 +02:00
Willem Wollebrants
43e9393009
Merge pull request #310 from sergiy-petrov/patch-1
test agains php 7.4
2020-03-05 20:31:19 +01:00
sergiy-petrov
7747441139
test agains php 7.4 2020-03-05 15:30:36 +02:00
Willem Wollebrants
87f830e554
Merge pull request #306 from vlucas/optionals
make selection of which rules to run more clear
2020-02-14 15:19:19 +01:00
Willem Wollebrants
cb2787cfcc make selection of which rules to run more clear 2020-02-14 15:08:39 +01:00
Willem Wollebrants
2baace22d8 correct documentation for integer strict mode, see #302 2020-02-14 09:44:44 +01:00
Vance Lucas
d0134c33d2
Merge pull request #293 from aecy/master
update: more french added
2019-10-24 09:46:33 -05:00
aecyM^
b7c5c09912
update: more french added 2019-09-07 15:12:40 +02:00
Vance Lucas
849d7e7dfb
Add Tidelife support message 2019-08-29 16:21:26 -05:00
Vance Lucas
47af606520
Add Security notice 2019-08-29 16:18:29 -05:00
20 changed files with 480 additions and 203 deletions

73
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,73 @@
name: Run Tests
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.operating-system }}
strategy:
matrix:
operating-system: ['ubuntu-latest']
php-versions:
- '5.4'
- '5.5'
- '5.6'
- '7.0'
- '7.1'
- '7.2'
- '7.3'
- '7.4'
- '8.0'
# - '8.1'
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
- name: Cache composer packages
id: composer-cache
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php-versions }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php-versions }}-
- name: Validate composer configuration
run: |
composer validate
- name: Install dependencies
run: |
composer install --no-progress
- name: Run tests
run: |
composer run-script test
# test-hhvm:
# runs-on: ubuntu-latest
# steps:
# - name: Checkout
# uses: actions/checkout@v2
# - name: Setup HHVM
# uses: azjezz/setup-hhvm@v1
# with:
# version: latest
# debug: false
# - name: Cache composer packages
# id: composer-cache
# uses: actions/cache@v2
# with:
# path: vendor
# key: ${{ runner.os }}-hhvm-${{ hashFiles('**/composer.lock') }}
# restore-keys: |
# ${{ runner.os }}-hhvm-
# - name: Validate composer configuration
# run: |
# composer validate
# - name: Install dependencies
# run: |
# composer install --no-progress
# - name: Run tests
# run: |
# composer run-script test

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ composer.phar
composer.lock
vendor
.idea/
.phpunit.result.cache

View File

@ -1,31 +0,0 @@
#see https://travis-ci.community/t/php-5-4-and-5-5-archives-missing/3723
dist: trusty
# see http://about.travis-ci.org/docs/user/languages/php/ for more hints
language: php
# list any PHP version you want to test against
php:
- 5.4
- 5.5
- 5.6
- 7.0
- 7.1
- 7.2
- 7.3
- nightly
- hhvm
matrix:
allow_failures:
- php: hhvm
- php: nightly
include:
- php: 5.3
dist: precise
before_script:
- composer install
# Script to run tests
script: composer test

View File

@ -6,10 +6,12 @@ methods with a focus on readable and concise syntax. Valitron is the
simple and pragmatic validation library you've been looking for.
[![Build
Status](https://travis-ci.org/vlucas/valitron.png?branch=master)](https://travis-ci.org/vlucas/valitron)
Status](https://github.com/vlucas/valitron/actions/workflows/test.yml/badge.svg)](https://github.com/vlucas/valitron/actions/workflows/test.yml)
[![Latest Stable Version](https://poser.pugx.org/vlucas/valitron/v/stable.png)](https://packagist.org/packages/vlucas/valitron)
[![Total Downloads](https://poser.pugx.org/vlucas/valitron/downloads.png)](https://packagist.org/packages/vlucas/valitron)
[Get supported vlucas/valitron with the Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-vlucas-valitron?utm_source=packagist-vlucas-valitron&utm_medium=referral&utm_campaign=readme)
## Why Valitron?
Valitron was created out of frustration with other validation libraries
@ -125,6 +127,33 @@ V::lang('ar');
```
Disabling the {field} name in the output of the error message.
```php
use Valitron\Validator as V;
$v = new Valitron\Validator(['name' => 'John']);
$v->rule('required', ['name']);
// Disable prepending the labels
$v->setPrependLabels(false);
// Error output for the "false" condition
[
["name"] => [
"is required"
]
]
// Error output for the default (true) condition
[
["name"] => [
"name is required"
]
]
```
You can conditionally require values using required conditional rules. In this example, for authentication, we're requiring either a token when both the email and password are not present, or a password when the email address is present.
```php
// this rule set would work for either data set...
@ -438,24 +467,19 @@ $v->rules([
$v->validate();
```
*Note* the optional boolean flag for strict mode will allow for integers to be supplied as negative values. So the following rule would evaluate to true:
*Note* the optional boolean flag for strict mode makes sure integers are to be supplied in a strictly numeric form. So the following rule would evaluate to true:
```php
$v = new Valitron\Validator(['age' => '-27']);
$v->rules([
'integer' => [
['age', true]
]
]);
$v = new Valitron\Validator(['negative' => '-27', 'positive'=>'27']);
$v->rule('integer', 'age', true);
$v->rule('integer', 'height', true);
$v->validate();
```
Whereas the same for a positive (+) value would evaluate to false, as the + in this case is redundant:
Whereas the following will evaluate to false, as the + for the positive number in this case is redundant:
```php
$v = new Valitron\Validator(['age' => '+27']);
$v->rules([
'integer' => [
['age', true]
]
]);
$v = new Valitron\Validator(['negative' => '-27', 'positive'=>'+27']);
$v->rule('integer', 'age', true);
$v->rule('integer', 'height', true);
$v->validate();
```
@ -1121,7 +1145,7 @@ $v = new Valitron\Validator([
'city' => 'Doe D.C.'
]
]);
$v->rule(['arrayHasKeys', 'address', ['name', 'street', 'city']);
$v->rule('arrayHasKeys', 'address', ['name', 'street', 'city']);
$v->validate();
```
@ -1324,3 +1348,7 @@ 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
## Security Disclosures and Contact Information
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.

View File

@ -3,20 +3,20 @@
"type": "library",
"description": "Simple, elegant, stand-alone validation library with NO dependencies",
"keywords": ["validation", "validator", "valid"],
"homepage": "http://github.com/vlucas/valitron",
"homepage": "https://github.com/vlucas/valitron",
"license": "BSD-3-Clause",
"authors": [
{
"name": "Vance Lucas",
"email": "vance@vancelucas.com",
"homepage": "http://www.vancelucas.com"
"homepage": "https://www.vancelucas.com"
}
],
"require": {
"php": ">=5.3.2"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35 || ^5.5 || ^6.5"
"phpunit/phpunit": ">=4.8.35"
},
"suggest": {
"ext-mbstring": "It can support the multiple bytes string length."

42
lang/fa.php Normal file
View File

@ -0,0 +1,42 @@
<?php
return array(
'required' => "الزامی است",
'equals' => " باید برابر باشد با '%s'",
'different' => "باید متفاوت باشد از '%s'",
'accepted' => "باید پذیرفته شده باشد",
'numeric' => "باید مقدار عددی باشد",
'integer' => "باید عددی طبیعی باشد",
'length' => "طول باید %d باشد",
'min' => "حداقل باید %s کاراکتر باشد",
'max' => "نباید بیشتر از %s کارکتر باشد",
'listContains' => "حاوی مقدار نامعتبر",
'in' => "حاوی مقدار نامعتبر",
'notIn' => "حاوی مقدار نامعتبر",
'ip' => " آدرس معتبر نیست IP",
'ipv4' => "آدرس معتبر نیست IPv4",
'ipv6' => "آدرس معتبر نیست IPv6",
'email' => "آدرس ایمیل معتبر نیست",
'url' => "معتبر نیست URL",
'urlActive' => "دامنه باید فعال باشد",
'alpha' => "باید حاوی حروف a-z باشد",
'alphaNum' => "باید حاوی حروف a-z و/یا اعداد 0-9 باشد",
'slug' => "باید حاوی حروف a-z, اعداد 0-9, دش و آندراسکور باشد",
'regex' => "حاوی کارکترهای نامعتبر",
'date' => "تاریخ معتبر نیست",
'dateFormat' => "فرمت تاریخ باید به این شکل '%s' باشد",
'dateBefore' => "تاریخ باید قبل از '%s' باشد",
'dateAfter' => "تاریخ باید بعد از '%s' باشد",
'contains' => "باید حاوی %s باشد",
'boolean' => "مقدار باید بولین باشد",
'lengthBetween' => "طول باید بین %d و %d کاراکتر باشد",
'creditCard' => "شماره کارت اعتباری معتبر نیست",
'lengthMin' => "طول باید حداقل %d کاراکتر باشد",
'lengthMax' => "طول نباید بیشتر از %d کاراکتر باشد",
'instanceOf' => "باید آبجکتی از نوع '%s' باشد",
'containsUnique' => "باید حاوی المان ها یونیک باشد",
'requiredWith' => "الزامی است",
'requiredWithout'=> "الزامی است",
'subset' => "حاوی آیتمی است که در لیست موجود نیست",
'arrayHasKeys' => "همه کلیدهای الزامی را ندارد",
);

View File

@ -1,35 +1,40 @@
<?php
return array(
'required' => "est obligatoire",
'equals' => "doit être identique à '%s'",
'different' => "doit être différent de '%s'",
'accepted' => "doit être accepté",
'numeric' => "doit être numérique",
'integer' => "doit être un entier",
'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",
'email' => "n'est pas une adresse email valide",
'url' => "n'est pas une URL",
'urlActive' => "doit être un domaine actif",
'alpha' => "doit contenir uniquement les lettres a-z",
'alphaNum' => "doit contenir uniquement des lettres de a-z et/ou des chiffres 0-9",
'slug' => "doit contenir uniquement des lettres de a-z, des chiffres 0-9, des tirets et des traits soulignés",
'regex' => "contient des caractères invalides",
'date' => "n'est pas une date valide",
'dateFormat' => "doit être une date avec le format '%s'",
'dateBefore' => "doit être une date avant '%s'",
'dateAfter' => "doit être une date après '%s'",
'contains' => "doit contenir %s",
'boolean' => "doit être un booléen",
'lengthBetween' => "doit être entre %d et %d caractères",
'creditCard' => "doit être un numéro de carte de crédit valide",
'lengthMin' => "doit avoir au moins %d caractères",
'lengthMax' => "ne doit pas dépasser %d caractères",
'instanceOf' => "doit être une instance de '%s'"
return array(
'required' => "est obligatoire",
'equals' => "doit être identique à '%s'",
'different' => "doit être différent de '%s'",
'accepted' => "doit être accepté",
'numeric' => "doit être numérique",
'integer' => "doit être un entier",
'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",
'email' => "n'est pas une adresse email valide",
'url' => "n'est pas une URL",
'urlActive' => "doit être un domaine actif",
'alpha' => "doit contenir uniquement les lettres a-z",
'alphaNum' => "doit contenir uniquement des lettres de a-z et/ou des chiffres 0-9",
'slug' => "doit contenir uniquement des lettres de a-z, des chiffres 0-9, des tirets et des traits soulignés",
'regex' => "contient des caractères invalides",
'date' => "n'est pas une date valide",
'dateFormat' => "doit être une date avec le format '%s'",
'dateBefore' => "doit être une date avant '%s'",
'dateAfter' => "doit être une date après '%s'",
'contains' => "doit contenir %s",
'boolean' => "doit être un booléen",
'lengthBetween' => "doit être entre %d et %d caractères",
'creditCard' => "doit être un numéro de carte de crédit valide",
'lengthMin' => "doit avoir au moins %d caractères",
'lengthMax' => "ne doit pas dépasser %d caractères",
'instanceOf' => "doit être une instance de '%s'",
"containsUnique" => "doit contenir des élements unique",
"requiredWith" => "est requis",
"requiredWithout" => "est requis",
"subset" => "contient un élement qui n'est pas dans la liste",
"arrayHasKeys" => "ne contient pas toutes les clés requises"
);

View File

@ -1,35 +1,42 @@
<?php
return array(
'required' => "を入力してください",
'equals' => "は「%s」と同じ内容を入力してください",
'different' => "は「%s」と異なる内容を入力してください",
'accepted' => "に同意してください",
'numeric' => "は数値を入力してください",
'integer' => "は半角数字で入力してください",
'length' => "は%d文字で入力してください",
'min' => "には%sより大きな値を入力してください",
'max' => "には%sより小さな値を入力してください",
'listContains' => "には選択できない値が含まれています",
'in' => "には選択できない値が含まれています",
'notIn' => "には選択できない値が含まれています",
'ip' => "はIPアドレスの書式として正しくありません",
'email' => "はメールアドレスの書式として正しくありません",
'url' => "はURLの書式として正しくありません",
'urlActive' => "はアクティブなドメインではありません",
'alpha' => "は半角英字で入力してください",
'alphaNum' => "は半角英数字で入力してください",
'slug' => "は半角英数字、もしくは「-」「_」の文字で入力してください",
'regex' => "の書式が正しくありません",
'date' => "は日付の書式として正しくありません",
'dateFormat' => "は「%s」の書式で日付を入力してください",
'dateBefore' => "は「%s」以前の日付を入力してください",
'dateAfter' => "は「%s」以後の日付を入力してください",
'contains' => "は「%s」を含んでいなければいけません",
'boolean' => "は真偽値である必要があります",
'lengthBetween' => "は%d〜%d文字で入力してください",
'creditCard' => "はクレジットカード番号の書式として正しくありません",
'lengthMin' => "は%d文字以上入力してください",
'lengthMax' => "は%d文字以内で入力してください",
'instanceOf' => "は「%s」のインスタンスではありません",
'required' => "を入力してください",
'equals' => "は「%s」と同じ内容を入力してください",
'different' => "は「%s」と異なる内容を入力してください",
'accepted' => "に同意してください",
'numeric' => "は数値を入力してください",
'integer' => "は半角数字で入力してください",
'length' => "は%d文字で入力してください",
'min' => "には%sより大きな値を入力してください",
'max' => "には%sより小さな値を入力してください",
'listContains' => "には選択できない値が含まれています",
'in' => "には選択できない値が含まれています",
'notIn' => "には選択できない値が含まれています",
'ip' => "はIPアドレスの書式として正しくありません",
'ipv4' => "はIPv4のIPアドレスの書式として正しくありません",
'ipv6' => "はIPv6のIPアドレスの書式として正しくありません",
'email' => "はメールアドレスの書式として正しくありません",
'url' => "はURLの書式として正しくありません",
'urlActive' => "はアクティブなドメインではありません",
'alpha' => "は半角英字で入力してください",
'alphaNum' => "は半角英数字で入力してください",
'slug' => "は半角英数字、もしくは「-」「_」の文字で入力してください",
'regex' => "の書式が正しくありません",
'date' => "は日付の書式として正しくありません",
'dateFormat' => "は「%s」の書式で日付を入力してください",
'dateBefore' => "は「%s」以前の日付を入力してください",
'dateAfter' => "は「%s」以後の日付を入力してください",
'contains' => "は「%s」を含んでいなければいけません",
'boolean' => "は真偽値である必要があります",
'lengthBetween' => "は%d〜%d文字で入力してください",
'creditCard' => "はクレジットカード番号の書式として正しくありません",
'lengthMin' => "は%d文字以上入力してください",
'lengthMax' => "は%d文字以内で入力してください",
'instanceOf' => "は「%s」のインスタンスではありません",
'containsUnique' => "は重複のないように入力してください",
'requiredWith' => "を入力してください",
'requiredWithout' => "を入力してください",
'subset' => "には選択できない値が含まれています",
'arrayHasKeys' => "の必要な項目が選択されていません",
);

42
lang/sl.php Normal file
View File

@ -0,0 +1,42 @@
<?php
return array(
'required' => "potrebno",
'equals' => "mora biti enak '% s'",
'different' => "mora biti drugačen od '% s'",
'accepted' => "mora biti označeno",
'numeric' => "mora biti številka",
'integer' => "mora biti celo število",
'length' => "ne sme biti daljši od% d",
'min' => "mora biti večji od% s",
'max' => "mora biti manjši od% s",
'listContains' => "vsebuje neveljavno vrednost",
'in' => "vsebuje neveljavno vrednost",
'notIn' => "vsebuje neveljavno vrednost",
'ip' => "ni veljaven naslov IP",
'ipv4' => "ni veljaven naslov IPv4",
'ipv6' => "ni veljaven naslov IPv6",
'email' => "ni veljaven e-poštni naslov",
'url' => "ni veljaven URL",
'urlActive' => "mora biti aktivna domena",
'alpha' => "mora vsebovati samo črke a-z",
'alphaNum' => "mora vsebovati samo črke a-z in / ali številke 0-9",
'slug' => "mora vsebovati samo črke a-z, številke 0-9, črtice in podčrtaje",
'regex' => "vsebuje neveljavne znake",
'date' => "ni veljaven datum",
'dateFormat' => "mora biti datum s formatom '% s'",
'dateBefore' => "mora biti datum pred '% s'",
'dateAfter' => "mora biti datum za '% s'",
'contains' => "mora vsebovati% s",
'boolean' => "mora biti boolean",
'lengthBetween' => "mora biti med% d in% d znaki",
'creditCard' => "mora biti veljavna številka kreditne kartice",
'lengthMin' => "mora biti dolg vsaj% d znakov",
'lengthMax' => "ne sme presegati% d znakov",
'instanceOf' => "mora biti primerek '% s'",
'containsUnique' => "mora vsebovati samo edinstvene elemente",
'requiredWith' => "je potrebno",
'requiredWithout'=> "je potrebno",
'subset' => "vsebuje element, ki ga ni na seznamu",
'arrayHasKeys' => "ne vsebuje vseh potrebnih tipk",
);

View File

@ -13,23 +13,23 @@ return array(
'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",
'email' => "är inte en giltlig e-postadress",
'url' => "är inte en giltlig URL",
'ip' => "är inte en giltig IP-adress",
'email' => "är inte en giltig e-postadress",
'url' => "är inte en giltig URL",
'urlActive' => "måste vara ett aktivt domännamn",
'alpha' => "får bara inehålla bokstäver a-z",
'alphaNum' => "får bara inehålla bokstäver a-z och/eller siffror 0-9",
'slug' => "får bara inehålla bokstäver a-z och/eller siffror 0-9, bindesträck og understräck",
'regex' => "inehåller ogiltliga tecken",
'date' => "är inte ett giltligt datum",
'alpha' => "får bara innehålla bokstäver a-z",
'alphaNum' => "får bara innehålla bokstäver a-z och/eller siffror 0-9",
'slug' => "får bara innehålla bokstäver a-z och/eller siffror 0-9, bindesstreck och understreck",
'regex' => "innehåller ogiltiga tecken",
'date' => "är inte ett giltigt datum",
'dateFormat' => "måste vara ett datum med formatet '%s'",
'dateBefore' => "måste vara ett datum före '%s'",
'dateAfter' => "måste vara ett datum efter '%s'",
'contains' => "måste innehålla %s",
'boolean' => "måste vara ett booleskt värde",
'lengthBetween' => "måste vara mellan %d och %d tecken långt",
'creditCard' => "måste vara et gyldig kredittkortnummer",
'creditCard' => "måste vara ett giltigt kreditkortsnummer",
'lengthMin' => "måste vara minst %d tecken långt",
'lengthMax' => "får itne överstiga %d tecken",
'lengthMax' => "får inte överstiga %d tecken",
'instanceOf' => "måste vara en instans av '%s'"
);

View File

@ -29,7 +29,7 @@ return array(
'boolean' => "boolean olmalı",
'lengthBetween' => "%d ve %d karakter arasında olmalı",
'creditCard' => "geçerli bir kredi kartı numarası olmalı",
"lengthMin" => "%d katakterden fazla içermeli",
"lengthMin" => "%d karakterden fazla içermeli",
"lengthMax" => "%d karakterden az içermeli",
"instanceOf" => "bunun bir örneği olmalı '%s'"
);

View File

@ -7,7 +7,7 @@ return array(
'accepted' => "必须接受",
'numeric' => "只能是数字",
'integer' => "只能是整数",
'length' => "长度必须于 %d",
'length' => "长度必须于 %d",
'min' => "必须大于 %s",
'max' => "必须小于 %s",
'listContains' => "无效的值",
@ -30,5 +30,11 @@ return array(
'lengthBetween' => "长度只能介于 %d 和 %d 之间",
'creditCard' => "信用卡号码不正确",
'lengthMin' => "长度必须大于 %d",
'lengthMax' => "长度必须小于 %d"
'lengthMax' => "长度必须小于 %d",
'instanceOf' => "必须是 '%s' 的实例",
'containsUnique' => "必须仅包含唯一的元素",
'requiredWith' => "是必须的",
'requiredWithout' => "是必须的",
'subset' => "包含不在列表中的项目",
'arrayHasKeys' => "不包含所有必需的键",
);

View File

@ -1,29 +1,40 @@
<?php
return array(
'required' => "不能為空",
'equals' => "必須和 '%s' 一致",
'different' => "必須和 '%s' 不一致",
'accepted' => "必須接受",
'numeric' => "只能是數字",
'integer' => "只能是整數",
'length' => "長度必須大於 %d",
'min' => "必須大於 %s",
'max' => "必須小於 %s",
'listContains' => "無效的值",
'in' => "無效的值",
'notIn' => "無效的值",
'ip' => "無效IP地址",
'email' => "無效郵箱地址",
'url' => "無效的URL",
'urlActive' => "必須是可用的域名",
'alpha' => "只能包括英文字母(a-z)",
'alphaNum' => "只能包括英文字母(a-z)和數字(0-9)",
'slug' => "只能包括英文字母(a-z)、數字(0-9)、破折號和下劃線",
'regex' => "無效格式",
'date' => "無效的日期",
'dateFormat' => "日期的格式應該為 '%s'",
'dateBefore' => "日期必須在 '%s' 之前",
'dateAfter' => "日期必須在 '%s' 之後",
'contains' => "必須包含 %s"
'required' => "不能為空",
'equals' => "必須和 '%s' 一致",
'different' => "必須和 '%s' 不一致",
'accepted' => "必須接受",
'numeric' => "只能是數字",
'integer' => "只能是整數",
'length' => "長度必須大於 %d",
'min' => "必須大於 %s",
'max' => "必須小於 %s",
'listContains' => "無效的值",
'in' => "無效的值",
'notIn' => "無效的值",
'ip' => "無效IP地址",
'email' => "無效郵箱地址",
'url' => "無效的URL",
'urlActive' => "必須是可用的域名",
'alpha' => "只能包括英文字母(a-z)",
'alphaNum' => "只能包括英文字母(a-z)和數字(0-9)",
'slug' => "只能包括英文字母(a-z)、數字(0-9)、破折號和下劃線",
'regex' => "無效格式",
'date' => "無效的日期",
'dateFormat' => "日期的格式應該為 '%s'",
'dateBefore' => "日期必須在 '%s' 之前",
'dateAfter' => "日期必須在 '%s' 之後",
'contains' => "必須包含 %s",
'boolean' => "必須是真或假",
'lengthBetween' => "長度只能介於 %d 和 %d 之間",
'creditCard' => "信用卡號碼不正確",
'lengthMin' => "長度必須大於 %d",
'lengthMax' => "長度必須小於 %d",
'instanceOf' => "必須是 '%s' 的實例",
'containsUnique' => "必須僅包含唯一的元素",
'requiredWith' => "是必須的",
'requiredWithout' => "是必須的",
'subset' => "包含不在列表中的項目",
'arrayHasKeys' => "不包含所有必需的鍵",
);

View File

@ -7,7 +7,6 @@
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php"
>
<testsuites>
@ -15,12 +14,4 @@
<directory suffix="Test.php">tests/Valitron</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
<blacklist>
<directory suffix=".php">vendor/</directory>
</blacklist>
</filter>
</phpunit>

View File

@ -83,6 +83,11 @@ class Validator
*/
protected $stop_on_first_fail = false;
/**
* @var bool
*/
protected $prepend_labels = true;
/**
* Setup validation
*
@ -144,6 +149,14 @@ class Validator
return static::$_langDir ?: dirname(dirname(__DIR__)) . '/lang';
}
/**
* @param bool $prepend_labels
*/
public function setPrependLabels($prepend_labels = true)
{
$this->prepend_labels = $prepend_labels;
}
/**
* Required field validator
*
@ -159,9 +172,7 @@ class Validator
return $find[1];
}
if (is_null($value)) {
return false;
} elseif (is_string($value) && trim($value) === '') {
if (is_null($value) || (is_string($value) && trim($value) === '')) {
return false;
}
@ -409,9 +420,13 @@ class Validator
*/
protected function validateIn($field, $value, $params)
{
$isAssoc = array_values($params[0]) !== $params[0];
if ($isAssoc) {
$params[0] = array_keys($params[0]);
$forceAsAssociative = false;
if (isset($params[2])) {
$forceAsAssociative = (bool) $params[2];
}
if ($forceAsAssociative || $this->isAssociativeArray($params[0])) {
$params[0] = array_keys($params[0]);
}
$strict = false;
@ -432,8 +447,12 @@ class Validator
*/
protected function validateListContains($field, $value, $params)
{
$isAssoc = array_values($value) !== $value;
if ($isAssoc) {
$forceAsAssociative = false;
if (isset($params[2])) {
$forceAsAssociative = (bool) $params[2];
}
if ($forceAsAssociative || $this->isAssociativeArray($value)) {
$value = array_keys($value);
}
@ -611,12 +630,17 @@ class Validator
*/
protected function validateEmailDNS($field, $value)
{
if (!is_string($value)) {
return false;
}
if ($this->validateEmail($field, $value)) {
$domain = ltrim(stristr($value, '@'), '@') . '.';
if (function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46')) {
$domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46);
}
return checkdnsrr($domain, 'ANY');
return checkdnsrr($domain, 'MX');
}
return false;
@ -631,6 +655,10 @@ class Validator
*/
protected function validateUrl($field, $value)
{
if (!is_string($value)) {
return false;
}
foreach ($this->validUrlPrefixes as $prefix) {
if (strpos($value, $prefix) !== false) {
return filter_var($value, \FILTER_VALIDATE_URL) !== false;
@ -649,6 +677,10 @@ class Validator
*/
protected function validateUrlActive($field, $value)
{
if (!is_string($value)) {
return false;
}
foreach ($this->validUrlPrefixes as $prefix) {
if (strpos($value, $prefix) !== false) {
$host = parse_url(strtolower($value), PHP_URL_HOST);
@ -877,11 +909,9 @@ class Validator
} elseif (isset($cards)) {
// if we have cards, check our users card against only the ones we have
foreach ($cards as $card) {
if (in_array($card, array_keys($cardRegex))) {
if (in_array($card, array_keys($cardRegex)) && preg_match($cardRegex[$card], $value) === 1) {
// if the card is valid, we want to stop looping
if (preg_match($cardRegex[$card], $value) === 1) {
return true;
}
return true;
}
}
} else {
@ -941,8 +971,8 @@ class Validator
$emptyFields = 0;
foreach ($reqParams as $requiredField) {
// check the field is set, not null, and not the empty string
if (isset($fields[$requiredField]) && !is_null($fields[$requiredField])
&& (is_string($fields[$requiredField]) ? trim($fields[$requiredField]) !== '' : true)) {
list($requiredFieldValue, $multiple) = $this->getPart($fields, explode('.', $requiredField));
if (isset($requiredFieldValue) && (!is_string($requiredFieldValue) || trim($requiredFieldValue) !== '')) {
if (!$allRequired) {
$conditionallyReq = true;
break;
@ -985,8 +1015,8 @@ class Validator
$filledFields = 0;
foreach ($reqParams as $requiredField) {
// check the field is NOT set, null, or the empty string, in which case we are requiring this value be present
if (!isset($fields[$requiredField]) || (is_null($fields[$requiredField])
|| (is_string($fields[$requiredField]) && trim($fields[$requiredField]) === ''))) {
list($requiredFieldValue, $multiple) = $this->getPart($fields, explode('.', $requiredField));
if (!isset($requiredFieldValue) || (is_string($requiredFieldValue) && trim($requiredFieldValue) === '')) {
if (!$allEmpty) {
$conditionallyReq = true;
break;
@ -1089,10 +1119,8 @@ class Validator
}
}
// Use custom label instead of field name if set
if (is_string($params[0])) {
if (isset($this->_labels[$param])) {
$param = $this->_labels[$param];
}
if (is_string($params[0]) && isset($this->_labels[$param])) {
$param = $this->_labels[$param];
}
$values[] = $param;
}
@ -1167,6 +1195,27 @@ class Validator
}
}
private function validationMustBeExcecuted($validation, $field, $values, $multiple){
//always excecute requiredWith(out) rules
if (in_array($validation['rule'], array('requiredWith', 'requiredWithout'))){
return true;
}
//do not execute if the field is optional and not set
if($this->hasRule('optional', $field) && ! isset($values)){
return false;
}
//ignore empty input, except for required and accepted rule
if (! $this->hasRule('required', $field) && ! in_array($validation['rule'], array('required', 'accepted'))){
if($multiple){
return count($values) != 0;
}
return (isset($values) && $values !== '');
}
return true;
}
/**
* Run validations and return boolean result
*
@ -1179,15 +1228,7 @@ class Validator
foreach ($v['fields'] as $field) {
list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field), false);
// Don't validate if the field is not required and the value is empty and we don't have a conditionally required rule present on the field
if (($this->hasRule('optional', $field) && isset($values))
|| ($this->hasRule('requiredWith', $field) || $this->hasRule('requiredWithout', $field))) {
//Continue with execution below if statement
} elseif (
$v['rule'] !== 'required' && !$this->hasRule('required', $field) &&
$v['rule'] !== 'accepted' &&
(!isset($values) || $values === '' || ($multiple && count($values) == 0))
) {
if (! $this->validationMustBeExcecuted($v, $field, $values, $multiple)){
continue;
}
@ -1265,10 +1306,8 @@ class Validator
protected function hasRule($name, $field)
{
foreach ($this->_validations as $validation) {
if ($validation['rule'] == $name) {
if (in_array($field, $validation['fields'])) {
return true;
}
if ($validation['rule'] == $name && in_array($field, $validation['fields'])) {
return true;
}
}
@ -1458,7 +1497,9 @@ class Validator
}
}
} else {
$message = str_replace('{field}', ucwords(str_replace('_', ' ', $field)), $message);
$message = $this->prepend_labels
? str_replace('{field}', ucwords(str_replace('_', ' ', $field)), $message)
: str_replace('{field} ', '', $message);
}
return $message;
@ -1545,4 +1586,9 @@ class Validator
$me->mapFieldRules($field, $rules[$field]);
}, array_keys($rules));
}
private function isAssociativeArray($input){
//array contains at least one key that's not an can not be cast to an integer
return count(array_filter(array_keys($input), 'is_string')) > 0;
}
}

View File

@ -4,10 +4,8 @@ use PHPUnit\Framework\TestCase;
class BaseTestCase extends TestCase
{
public function setUp()
{
}
/*
public function tearDown()
{
$this->resetProperty('_lang');
@ -23,4 +21,5 @@ class BaseTestCase extends TestCase
$prop->setValue($value);
$prop->setAccessible(false);
}
*/
}

View File

@ -12,6 +12,19 @@ class ErrorMessagesTest extends BaseTestCase
$this->assertSame(array("Name is required"), $v->errors('name'));
}
/**
* Test the disabling of prepending the field labels
* to error messages.
*/
public function testErrorMessageExcludeFieldName()
{
$v = new Validator(array());
$v->setPrependLabels(false);
$v->rule('required', 'name');
$v->validate();
$this->assertSame(array("is required"), $v->errors('name'));
}
public function testAccurateErrorMessageParams()
{
$v = new Validator(array('num' => 5));

View File

@ -15,8 +15,8 @@ class LangTest extends BaseTestCase
{
$lang = 'ar';
Validator::lang($lang);
$validator = new Validator(array());
$this->assertEquals($lang, Validator::lang());
Validator::lang('en');
}
/**
@ -42,13 +42,15 @@ class LangTest extends BaseTestCase
$this->assertEquals(realpath($this->getLangDir()), realpath(Validator::langDir()));
}
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Fail to load language file '/this/dir/does/not/exists/en.php'
*/
public function testLangException()
{
try{
new Validator(array(), array(), 'en', '/this/dir/does/not/exists');
} catch (Exception $exception){
$this->assertInstanceOf("InvalidArgumentException", $exception);
$this->assertEquals("Fail to load language file '/this/dir/does/not/exists/en.php'", $exception->getMessage());
}
}

View File

@ -10,6 +10,7 @@ class StaticVsInstanceTest extends BaseTestCase
$this->assertEquals(
'ar', Validator::lang(), 'instance defined lang should not replace static global lang'
);
Validator::lang('en');
}
/**

View File

@ -980,6 +980,7 @@ class ValidateTest extends BaseTestCase
array('color', array('blue', 'green', 'red', 'yellow'))
)
));
$this->assertFalse($v->validate());
}
public function testAsciiValid()
@ -2919,6 +2920,46 @@ class ValidateTest extends BaseTestCase
$v->rule('optional', 'address');
$this->assertTrue($v->validate());
}
/**
*
* @see https://github.com/vlucas/valitron/issues/332
*/
public function testInRuleSearchesValuesForNumericArray(){
$v = new Valitron\Validator(array('color' => 'purple'));
$v->rules(array(
'in' => array(
array('color', array(3=>'green', 2=>'purple'))
)
));
$this->assertTrue($v->validate());
}
public function testInRuleSearchesKeysForAssociativeArray(){
$v = new Valitron\Validator(array('color' => 'c-2'));
$v->rules(array(
'in' => array(
array('color', array('c-3'=>'green', 'c-2'=>'purple'))
)
));
$this->assertTrue($v->validate());
}
public function testInRuleSearchesKeysWhenForcedTo(){
$v = new Valitron\Validator(array('color' => 2));
$v->rules(array(
'in' => array(
array('color', array('3'=>'green', '2'=>'purple'), null, true)
)
));
$this->assertTrue($v->validate());
}
}
function sampleFunctionCallback($field, $value, array $params)