├── .gitignore
├── .travis.yml
├── README.md
├── composer.json
├── errors
├── en.php
└── fr.php
├── licence.txt
├── phpunit.xml
├── src
└── SimpleValidator
│ ├── SimpleValidatorException.php
│ └── Validator.php
└── unit-test
├── alpha.test.php
├── array_input.test.php
├── bootstrap.php
├── email.test.php
├── error_file.test.php
├── extended_class.test.php
├── input_name_param.test.php
├── integer.test.php
├── ip.test.php
├── multiple_parameter.test.php
├── required.test.php
└── url.test.php
/.gitignore:
--------------------------------------------------------------------------------
1 | nbproject
2 | test.php
3 | CustomValidator
4 | vendor
5 | .DS_Store
6 | preg_test.php
7 | composer.lock
8 | .idea
9 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: php
2 |
3 | php:
4 | - 5.4
5 | - 5.3
6 |
7 | before_script:
8 | - composer install
9 |
10 | script: phpunit -c phpunit.xml
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Simple Validator Documentation
2 |
3 | [](https://travis-ci.org/cangelis/simple-validator)
4 |
5 | Validation is the process that checks for correctness, meaningfulness and security of the input data.
6 | SimpleValidator is a library that handles validation process easily.
7 |
8 | ## Install
9 |
10 | ### Including to your current composer.json
11 |
12 | Add this line into `require` in your ***composer.json***:
13 |
14 | ```
15 | "simple-validator/simple-validator": "1.0.*"
16 | ```
17 |
18 | and call
19 |
20 | ```
21 | php composer.phar update
22 | ```
23 |
24 | ### Installing directly
25 |
26 | Download `composer.phar` and call
27 |
28 | ```
29 | php composer.phar install
30 | ```
31 |
32 | and use autoload.php to include the classes
33 |
34 | ```php
35 | require 'vendor/autoload.php'
36 | ```
37 |
38 | ## A few examples:
39 |
40 | ```php
41 | [
44 | 'required',
45 | 'alpha',
46 | 'max_length(50)'
47 | ],
48 | 'age' => [
49 | 'required',
50 | 'integer',
51 | ],
52 | 'email' => [
53 | 'required',
54 | 'email'
55 | ],
56 | 'password' => [
57 | 'required',
58 | 'equals(:password_verify)'
59 | ],
60 | 'password_verify' => [
61 | 'required'
62 | ]
63 | ];
64 | $validation_result = SimpleValidator\Validator::validate($_POST, $rules);
65 | if ($validation_result->isSuccess() == true) {
66 | echo "validation ok";
67 | } else {
68 | echo "validation not ok";
69 | var_dump($validation_result->getErrors());
70 | }
71 | ```
72 |
73 | ## Custom Rules with anonymous functions
74 |
75 | Anonymous functions make the custom validations easier to be implemented.
76 |
77 | ### Example
78 |
79 | ```php
80 | $rules = [
81 | 'id' => [
82 | 'required',
83 | 'integer',
84 | 'post_exists' => function($input) {
85 | $query = mysqli_query("SELECT * FROM post WHERE id = " . $input);
86 | if (mysqli_num_rows($query) == 0)
87 | return false;
88 | return true;
89 | },
90 | 'between(5,15)' => function($input, $param1, $param2) {
91 | if (($input > $param1) && ($input < $param2))
92 | return true;
93 | return false;
94 | }
95 | ]
96 | ];
97 | ```
98 |
99 | and you need to add an error text for your rule to the error file (default: errors/en.php).
100 |
101 | ```php
102 | 'post_exists' => "Post does not exist"
103 | ```
104 |
105 | or add a custom error text for that rule
106 |
107 | ```php
108 | $validation_result->customErrors([
109 | 'post_exists' => 'Post does not exist'
110 | ]);
111 | ```
112 |
113 | ### Another example to understand scoping issue
114 |
115 | ```php
116 | // my local variable
117 | $var_to_compare = "1234";
118 | $rules = [
119 | 'password' => [
120 | 'required',
121 | 'integer',
122 | // pass my local variable to anonymous function
123 | 'is_match' => function($input) use (&$var_to_compare) {
124 | if ($var_to_compare == $input)
125 | return true;
126 | return false;
127 | }
128 | ]
129 | ];
130 | ```
131 |
132 | ## Custom Validators
133 |
134 | You can assume SimpleValidator as a tool or an interface to create a validator for yourself.
135 |
136 | Custom validators can have their own rules, own error files or default language definitions. In addition, you can override default rules in your custom validator.
137 |
138 | ```php
139 |
140 | class MyValidator extends \SimpleValidator\Validator {
141 |
142 | // methods have to be static !!!
143 | protected static function is_awesome($input) {
144 | if ($input == "awesome")
145 | return true;
146 | return false;
147 | }
148 |
149 | // overriding a default rule (url)
150 | protected static function url($input) {
151 | return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $input);
152 | }
153 |
154 | // set default language for your validator
155 | // if you don't override this method, the default language is "en"
156 | protected function getDefaultLang() {
157 | return getMyApplicationsDefaultLanguage();
158 | }
159 |
160 | // defining error files for your validator
161 | // in this example your files should live in "{class_path}/errors/{language}/validator.php
162 | protected function getErrorFilePath($lang) {
163 | return __DIR__ . "/errors/" . $lang . "/validator.php";
164 | }
165 |
166 | }
167 |
168 | ```
169 |
170 | **Create an error file:**
171 |
172 | ```php
173 | return [
174 | 'is_awesome' => 'the :attribute is not awesome'
175 | // error text for url is already defined in default error text file you don't have to define it here, but optionally you can
176 | ];
177 | ```
178 |
179 | And then, call the `validate` method.
180 |
181 | ```php
182 | $rules = [
183 | 'website' => [
184 | 'is_awesome',
185 | 'url'
186 | ]
187 | ];
188 | $validation_result = MyValidator::validate($_POST, $rules);
189 | ```
190 |
191 | ## Custom Rule parameters
192 |
193 | A rule can have multiple parameters. An example:
194 |
195 | ```php
196 | $rule = [
197 | 'id' => [
198 | 'rule1(:input1,:input2,2,5,:input3)' => function($input, $input1, $input2, $value1, $value2, $input3) {
199 | // validation here
200 | }
201 | ],
202 | // and so on..
203 | ];
204 |
205 |
206 | ```
207 |
208 | ## Custom Error messages
209 |
210 | ### Using Error file
211 | Custom rules provides localization for the error messages.
212 | Create a new file under **errors** folder, example: ```errors/es.php```
213 | and call ```getErrors()``` method using:
214 |
215 | ```php
216 | $validation_result->getErrors('es');
217 | ```
218 | ### Using customErrors method
219 | You can add custom errors using customErrors method.
220 | #### Examples:
221 | ```php
222 | $validation_result->customErrors([
223 | // input_name.rule => error text
224 | 'website.required' => 'We need to know your web site',
225 | // rule => error text
226 | 'required' => ':attribute field is required',
227 | 'name.alpha' => 'Name field must contain alphabetical characters',
228 | 'email_addr.email' => 'Email should be valid',
229 | 'email_addr.min_length' => 'Hey! Email is shorter than :params(0)',
230 | 'min_length' => ':attribute must be longer than :params(0)'
231 | ]);
232 | ```
233 | ## Naming Inputs
234 |
235 | ```php
236 | $naming => [
237 | 'name' => 'Name',
238 | 'url' => 'Web Site',
239 | 'password' => 'Password',
240 | 'password_verify' => 'Password Verification'
241 | ];
242 | $validation_result = SimpleValidator\Validator::validate($_POST, $rules, $naming);
243 | ```
244 | #### Output sample:
245 |
246 | * Name field is required -instead of "name field is required"-
247 | * Web Site field is required -instead of "url field is required"-
248 | * Password field should be same as Password Verification -equals(:password_verify) rule-
249 |
250 | ## More
251 |
252 | You can explicitly check out the validations using `has` method that might be useful for Unit Testing purposes.
253 |
254 |
255 | ```php
256 | // All return boolean
257 | $validation_result->has('email');
258 | $validation_result->has('email','required');
259 | $validation_result->has('password','equals');
260 | ```
261 |
262 | ## Default validations
263 |
264 |
265 |
266 | Rule |
267 | Parameter |
268 | Description |
269 | Example |
270 |
271 |
272 | required |
273 | No |
274 | Returns FALSE if the input is empty |
275 | |
276 |
277 |
278 | numeric |
279 | No |
280 | Returns FALSE if the input is not numeric |
281 | |
282 |
283 |
284 | email |
285 | No |
286 | Returns FALSE if the input is not a valid email address |
287 | |
288 |
289 |
290 | integer |
291 | No |
292 | Returns FALSE if the input is not an integer value |
293 | |
294 |
295 |
296 | float |
297 | No |
298 | Returns FALSE if the input is not a float value |
299 | |
300 |
301 |
302 | alpha |
303 | No |
304 | Returns FALSE if the input contains non-alphabetical characters |
305 | |
306 |
307 |
308 | alpha_numeric |
309 | No |
310 | Returns FALSE if the input contains non-alphabetical and numeric characters |
311 | |
312 |
313 |
314 | ip |
315 | No |
316 | Returns FALSE if the input is not a valid IP (IPv6 supported) |
317 | |
318 |
319 |
320 | url |
321 | No |
322 | Returns FALSE if the input is not a valid URL |
323 | |
324 |
325 |
326 | max_length |
327 | Yes |
328 | Returns FALSE if the input is longer than the parameter |
329 | max_length(10) |
330 |
331 |
332 | min_length |
333 | Yes |
334 | Returns FALSE if the input is shorter than the parameter |
335 | min_length(10) |
336 |
337 |
338 | exact_length |
339 | Yes |
340 | Returns FALSE if the input is not exactly parameter value long |
341 | exact_length(10) |
342 |
343 |
344 | equals |
345 | Yes |
346 | Returns FALSE if the input is not same as the parameter |
347 | equals(:password_verify) or equals(foo) |
348 |
349 |
350 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "simple-validator/simple-validator",
3 | "description": "Yet another validation class for PHP",
4 | "authors": [
5 | {
6 | "name": "Can Gelis",
7 | "email": "geliscan@gmail.com"
8 | }
9 | ],
10 | "autoload": {
11 | "psr-0": {"SimpleValidator\\": "src/"}
12 | },
13 | "require": {
14 | "php": ">=5.3.0"
15 | },
16 | "license": "MIT"
17 | }
18 |
--------------------------------------------------------------------------------
/errors/en.php:
--------------------------------------------------------------------------------
1 | input name
4 | * :params => rule parameters ( eg: :params(0) = 10 of max_length(10) )
5 | */
6 | return array(
7 | 'required' => ':attribute field is required',
8 | 'integer' => ':attribute field must be an integer',
9 | 'float' => ':attribute field must be a float',
10 | 'numeric' => ':attribute field must be numeric',
11 | 'email' => ':attribute is not a valid email',
12 | 'alpha' => ':attribute field must be an alpha value',
13 | 'alpha_numeric' => ':attribute field must be alphanumeric',
14 | 'ip' => ':attribute must contain a valid IP',
15 | 'url' => ':attribute must contain a valid URL',
16 | 'max_length' => ':attribute can be maximum :params(0) character long',
17 | 'min_length' => ':attribute must be minimum :params(0) character long',
18 | 'exact_length' => ':attribute field must :params(0) character long',
19 | 'equals' => ':attribute field should be same as :params(0)'
20 | );
21 |
--------------------------------------------------------------------------------
/errors/fr.php:
--------------------------------------------------------------------------------
1 | input name
4 | * :params => rule parameters ( eg: :params(0) = 10 of max_length(10) )
5 | */
6 | return array(
7 | 'required' => 'Le champ :attribute est obligatoire',
8 | 'integer' => 'Le champ :attribute doit être un entier',
9 | 'float' => 'Le champ :attribute doit être un décimal',
10 | 'numeric' => 'Le champ :attribute doit être numérique',
11 | 'email' => ':attribute n\'est pas une adresse email valide',
12 | 'alpha' => 'Le champ :attribute doit être une valeur alpha',
13 | 'alpha_numeric' => 'Le champ :attribute doit être une valeur alphanumérique',
14 | 'ip' => ':attribute doit contenir une IP valide',
15 | 'url' => ':attribute doit contenir une URL valide',
16 | 'max_length' => 'Le champ :attribute peut avoir au maximum :params(0) caractères',
17 | 'min_length' => 'Le champ :attribute doit avoir au minimum :params(0) caractères',
18 | 'exact_length' => 'Le champ :attribute doit avoir :params(0) caractères',
19 | 'equals' => 'Le champ :attribute doit être le même que :params(0)'
20 | );
21 |
--------------------------------------------------------------------------------
/licence.txt:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 | Copyright (c) 2013 Can Geliş
3 |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5 |
6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7 |
8 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 | ./unit-test
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/src/SimpleValidator/SimpleValidatorException.php:
--------------------------------------------------------------------------------
1 | "Error text could not found for ':param', or Error file could not found",
17 | static::STATIC_METHOD => "The method :param should be static",
18 | static::UNKNOWN_RULE => "Unknown Rule: :param",
19 | static::ARRAY_EXPECTED => "Rules are expected to Array. Input Name: :param"
20 | );
21 | parent::__construct(str_replace(":param", $param, static::$error_messages[$code]), $code);
22 | }
23 |
24 | }
25 |
26 | ?>
27 |
--------------------------------------------------------------------------------
/src/SimpleValidator/Validator.php:
--------------------------------------------------------------------------------
1 |
8 | * @copyright (c) 2013, Can Geliş
9 | * @license https://github.com/cangelis/simple-validator/blob/master/licence.txt MIT Licence
10 | * @link https://github.com/cangelis/simple-validator
11 | */
12 |
13 | /**
14 | * TODO: Exception handling for rules with parameters
15 | * TODO: unit tests for numeric, float, alpha_numeric, max_length, min_length, exact_length
16 | * TODO: add protection filters for several input vulnerabilities.
17 | */
18 | class Validator {
19 |
20 | protected $errors = array();
21 | protected $namings = array();
22 | protected $customErrorsWithInputName = array();
23 | protected $customErrors = array();
24 |
25 | /**
26 | * Constructor is not allowed because SimpleValidator uses its own
27 | * static method to instantiate the validaton
28 | */
29 | private function __construct($errors, $namings) {
30 | $this->errors = (array) $errors;
31 | $this->namings = (array) $namings;
32 | }
33 |
34 | /**
35 | *
36 | * @return boolean
37 | */
38 | public function isSuccess() {
39 | return (empty($this->errors) == true);
40 | }
41 |
42 | /**
43 | *
44 | * @param Array $errors_array
45 | */
46 | public function customErrors($errors_array) {
47 | foreach ($errors_array as $key => $value) {
48 | // handle input.rule eg (name.required)
49 | if (preg_match("#^(.+?)\.(.+?)$#", $key, $matches)) {
50 | // $this->customErrorsWithInputName[name][required] = error message
51 | $this->customErrorsWithInputName[(string) $matches[1]][(string) $matches[2]] = $value;
52 | } else {
53 | $this->customErrors[(string) $key] = $value;
54 | }
55 | }
56 | }
57 |
58 | protected function getDefaultLang() {
59 | return "en";
60 | }
61 |
62 | protected function getErrorFilePath($lang) {
63 | return null;
64 | }
65 |
66 | protected function getDefaultErrorTexts($lang = null) {
67 | /* handle default error text file */
68 | $default_error_texts = array();
69 | if (file_exists(__DIR__ . "/../../errors/" . $lang . ".php")) {
70 | $default_error_texts = include(__DIR__ . "/../../errors/" . $lang . ".php");
71 | }
72 | return $default_error_texts;
73 | }
74 |
75 | protected function getCustomErrorTexts($lang = null) {
76 | /* handle error text file for custom validators */
77 | $custom_error_texts = array();
78 | if (file_exists($this->getErrorFilePath($lang)))
79 | $custom_error_texts = include($this->getErrorFilePath($lang));
80 | return $custom_error_texts;
81 | }
82 |
83 | protected function handleNaming($input_name) {
84 | if (isset($this->namings[(string) $input_name])) {
85 | $named_input = $this->namings[(string) $input_name];
86 | } else {
87 | $named_input = $input_name;
88 | }
89 | return $named_input;
90 | }
91 |
92 | protected function handleParameterNaming($params) {
93 | foreach ($params as $key => $param) {
94 | if (preg_match("#^:([a-zA-Z0-9_]+)$#", $param, $param_type)) {
95 | if (isset($this->namings[(string) $param_type[1]]))
96 | $params[$key] = $this->namings[(string) $param_type[1]];
97 | else
98 | $params[$key] = $param_type[1];
99 | }
100 | }
101 | return $params;
102 | }
103 |
104 | /**
105 | *
106 | * @param string $error_file
107 | * @return array
108 | * @throws SimpleValidatorException
109 | */
110 | public function getErrors($lang = null) {
111 | if ($lang == null)
112 | $lang = $this->getDefaultLang();
113 |
114 | $error_results = array();
115 | $default_error_texts = $this->getDefaultErrorTexts($lang);
116 | $custom_error_texts = $this->getCustomErrorTexts($lang);
117 | foreach ($this->errors as $input_name => $results) {
118 | foreach ($results as $rule => $result) {
119 | $named_input = $this->handleNaming($input_name);
120 | /**
121 | * if parameters are input name they should be named as well
122 | */
123 | $result['params'] = $this->handleParameterNaming($result['params']);
124 | // if there is a custom message with input name, apply it
125 | if (isset($this->customErrorsWithInputName[(string) $input_name][(string) $rule])) {
126 | $error_message = $this->customErrorsWithInputName[(string) $input_name][(string) $rule];
127 | }
128 | // if there is a custom message for the rule, apply it
129 | else if (isset($this->customErrors[(string) $rule])) {
130 | $error_message = $this->customErrors[(string) $rule];
131 | }
132 | // if there is a custom validator try to fetch from its error file
133 | else if (isset($custom_error_texts[(string) $rule])) {
134 | $error_message = $custom_error_texts[(string) $rule];
135 | }
136 | // if none try to fetch from default error file
137 | else if (isset($default_error_texts[(string) $rule])) {
138 | $error_message = $default_error_texts[(string) $rule];
139 | } else {
140 | throw new SimpleValidatorException(SimpleValidatorException::NO_ERROR_TEXT, $rule);
141 | }
142 | /**
143 | * handle :params(..)
144 | */
145 | if (preg_match_all("#:params\((.+?)\)#", $error_message, $param_indexes))
146 | foreach ($param_indexes[1] as $param_index) {
147 | $error_message = str_replace(":params(" . $param_index . ")", $result['params'][$param_index], $error_message);
148 | }
149 | $error_results[] = str_replace(":attribute", $named_input, $error_message);
150 | }
151 | }
152 | return $error_results;
153 | }
154 |
155 | /**
156 | *
157 | * @return boolean
158 | */
159 | public function has($input_name, $rule_name = null) {
160 | if ($rule_name != null)
161 | return isset($this->errors[$input_name][$rule_name]);
162 | return isset($this->errors[$input_name]);
163 | }
164 |
165 | final public function getResults() {
166 | return $this->errors;
167 | }
168 |
169 | /**
170 | * Gets the parameter names of a rule
171 | * @param type $rule
172 | * @return mixed
173 | */
174 | private static function getParams($rule) {
175 | if (preg_match("#^([a-zA-Z0-9_]+)\((.+?)\)$#", $rule, $matches)) {
176 | return array(
177 | 'rule' => $matches[1],
178 | 'params' => explode(",", $matches[2])
179 | );
180 | }
181 | return array(
182 | 'rule' => $rule,
183 | 'params' => array()
184 | );
185 | }
186 |
187 | /**
188 | * Handle parameter with input name
189 | * eg: equals(:name)
190 | * @param mixed $params
191 | * @return mixed
192 | */
193 | private static function getParamValues($params, $inputs) {
194 | foreach ($params as $key => $param) {
195 | if (preg_match("#^:([\[\]a-zA-Z0-9_]+)$#", $param, $param_type)) {
196 | $params[$key] = @$inputs[(string) $param_type[1]];
197 | }
198 | }
199 | return $params;
200 | }
201 |
202 | /**
203 | *
204 | * @param Array $inputs
205 | * @param Array $rules
206 | * @param Array $naming
207 | * @return Validator
208 | * @throws SimpleValidatorException
209 | */
210 | public static function validate($inputs, $rules, $naming = null) {
211 | $errors = null;
212 | foreach ($rules as $input => $input_rules) {
213 | if (is_array($input_rules)) {
214 | foreach ($input_rules as $rule => $closure) {
215 | if (!isset($inputs[(string) $input]))
216 | $input_value = null;
217 | else
218 | $input_value = $inputs[(string) $input];
219 | /**
220 | * if the key of the $input_rules is numeric that means
221 | * it's neither an anonymous nor an user function.
222 | */
223 | if (is_numeric($rule)) {
224 | $rule = $closure;
225 | }
226 | $rule_and_params = static::getParams($rule);
227 | $params = $real_params = $rule_and_params['params'];
228 | $rule = $rule_and_params['rule'];
229 | $params = static::getParamValues($params, $inputs);
230 | array_unshift($params, $input_value);
231 | /**
232 | * Handle anonymous functions
233 | */
234 | if(is_object($closure) && get_class($closure) == 'Closure') {
235 | $refl_func = new \ReflectionFunction($closure);
236 | $validation = $refl_func->invokeArgs($params);
237 | }/**
238 | * handle class methods
239 | */ else if (@method_exists(get_called_class(), $rule)) {
240 | $refl = new \ReflectionMethod(get_called_class(), $rule);
241 | if ($refl->isStatic()) {
242 | $refl->setAccessible(true);
243 | $validation = $refl->invokeArgs(null, $params);
244 | } else {
245 | throw new SimpleValidatorException(SimpleValidatorException::STATIC_METHOD, $rule);
246 | }
247 | } else {
248 | throw new SimpleValidatorException(SimpleValidatorException::UNKNOWN_RULE, $rule);
249 | }
250 | if ($validation == false) {
251 | $errors[(string) $input][(string) $rule]['result'] = false;
252 | $errors[(string) $input][(string) $rule]['params'] = $real_params;
253 | }
254 | }
255 | } else {
256 | throw new SimpleValidatorException(SimpleValidatorException::ARRAY_EXPECTED, $input);
257 | }
258 | }
259 | return new static($errors, $naming);
260 | }
261 |
262 | protected static function required($input = null) {
263 | return (!is_null($input) && (trim($input) != ''));
264 | }
265 |
266 | protected static function numeric($input) {
267 | return is_numeric($input);
268 | }
269 |
270 | protected static function email($input) {
271 | return filter_var($input, FILTER_VALIDATE_EMAIL);
272 | }
273 |
274 | protected static function integer($input) {
275 | return is_int($input) || ($input == (string) (int) $input);
276 | }
277 |
278 | protected static function float($input) {
279 | return is_float($input) || ($input == (string) (float) $input);
280 | }
281 |
282 | protected static function alpha($input) {
283 | return (preg_match("#^[a-zA-ZÀ-ÿ]+$#", $input) == 1);
284 | }
285 |
286 | protected static function alpha_numeric($input) {
287 | return (preg_match("#^[a-zA-ZÀ-ÿ0-9]+$#", $input) == 1);
288 | }
289 |
290 | protected static function ip($input) {
291 | return filter_var($input, FILTER_VALIDATE_IP);
292 | }
293 |
294 | /*
295 | * TODO: need improvements for tel and urn urls.
296 | * check out url.test.php for the test result
297 | * urn syntax: http://www.faqs.org/rfcs/rfc2141.html
298 | *
299 | */
300 |
301 | protected static function url($input) {
302 | return filter_var($input, FILTER_VALIDATE_URL);
303 | }
304 |
305 | protected static function max_length($input, $length) {
306 | return (strlen($input) <= $length);
307 | }
308 |
309 | protected static function min_length($input, $length) {
310 | return (strlen($input) >= $length);
311 | }
312 |
313 | protected static function exact_length($input, $length) {
314 | return (strlen($input) == $length);
315 | }
316 |
317 | protected static function equals($input, $param) {
318 | return ($input == $param);
319 | }
320 |
321 | }
322 |
--------------------------------------------------------------------------------
/unit-test/alpha.test.php:
--------------------------------------------------------------------------------
1 | rules = array(
7 | 'test' => array('alpha')
8 | );
9 | }
10 |
11 | public function tearDown() {
12 |
13 | }
14 |
15 | public function testAlphaInput() {
16 | $inputs = array('test' => 'ABCDE');
17 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
18 | $this->assertEquals($validation_result->isSuccess(), true);
19 | }
20 |
21 | public function testAlphaNumericInput() {
22 | $inputs = array('test' => 'ABCDE123');
23 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
24 | $this->assertEquals($validation_result->isSuccess(), false);
25 | }
26 |
27 | public function testNonAlphaInput() {
28 | $inputs = array('test' => 'ABCDE123?!@');
29 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
30 | $this->assertEquals($validation_result->isSuccess(), false);
31 | }
32 |
33 | }
34 |
35 | ?>
36 |
--------------------------------------------------------------------------------
/unit-test/array_input.test.php:
--------------------------------------------------------------------------------
1 | rules = array(
7 | 'foo[bar]' => array('equals(:bar[baz])')
8 | );
9 | }
10 |
11 | public function testArrayInputValid() {
12 | $inputs = array(
13 | 'foo[bar]' => 'test1',
14 | 'bar[baz]' => 'test1'
15 | );
16 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
17 | $this->assertTrue($validation_result->isSuccess());
18 | }
19 |
20 | public function testArrayInputNotValid() {
21 | $inputs = array(
22 | 'foo[bar]' => 'test1',
23 | 'bar[baz]' => 'test2'
24 | );
25 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
26 | $this->assertFalse($validation_result->isSuccess());
27 | }
28 |
29 | }
30 |
31 | ?>
32 |
--------------------------------------------------------------------------------
/unit-test/bootstrap.php:
--------------------------------------------------------------------------------
1 |
5 |
--------------------------------------------------------------------------------
/unit-test/email.test.php:
--------------------------------------------------------------------------------
1 | rules = array(
7 | 'test' => array('email')
8 | );
9 | }
10 |
11 | public function tearDown() {
12 |
13 | }
14 |
15 | public function testValidEmail() {
16 | $inputs = array('test' => 'geliscan@gmail.com');
17 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
18 | $this->assertEquals($validation_result->isSuccess(), true);
19 | }
20 |
21 | public function testInvalidEmail() {
22 | $inputs = array('test' => 'SimpleValidator');
23 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
24 | $this->assertEquals($validation_result->isSuccess(), false);
25 | }
26 |
27 | public function testEmptyInput() {
28 | $inputs = array(
29 | 'test' => ''
30 | );
31 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
32 | $this->assertEquals($validator->isSuccess(), false);
33 | }
34 |
35 | public function testNullInput() {
36 | $inputs = array(
37 | 'test' => null
38 | );
39 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
40 | $this->assertEquals($validator->isSuccess(), false);
41 | }
42 |
43 | }
44 |
45 | ?>
46 |
--------------------------------------------------------------------------------
/unit-test/error_file.test.php:
--------------------------------------------------------------------------------
1 | array('required')));
7 | $this->assertEquals($validator->getErrors(), array('name field is required'));
8 | }
9 |
10 | public function testDefaultErrorFileInALevelAboveDirectory() {
11 | chdir("..");
12 | $validator = SimpleValidator\Validator::validate(array(), array('name' => array('required')));
13 | $this->assertEquals($validator->getErrors(), array('name field is required'));
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/unit-test/extended_class.test.php:
--------------------------------------------------------------------------------
1 | array(
38 | 'trueRule'
39 | )
40 | );
41 | try {
42 | CustomValidator::validate(null, $rules);
43 | } catch (SimpleValidator\SimpleValidatorException $e) {
44 | if ($e->getCode() == SimpleValidator\SimpleValidatorException::STATIC_METHOD)
45 | return;
46 | else
47 | $this->fail("Wrong Exception Code: " . $e->getCode());
48 | }
49 | $this->fail("Could not catched Exception");
50 | }
51 |
52 | public function testValidAndStaticMethodRule() {
53 | $rules = array(
54 | 'name' => array(
55 | 'trueStaticRule'
56 | )
57 | );
58 | try {
59 | $validation_result = CustomValidator::validate(null, $rules);
60 | $this->assertTrue($validation_result->isSuccess());
61 | } catch (SimpleValidator\SimpleValidatorException $e) {
62 | $this->fail("Exception occured: " . $e->getMessage());
63 | }
64 | return;
65 | }
66 |
67 | public function testInValidAndStaticMethodRule() {
68 | $rules = array(
69 | 'name' => array(
70 | 'falseStaticRule'
71 | )
72 | );
73 | try {
74 | $validation_result = CustomValidator::validate(null, $rules);
75 | $this->assertFalse($validation_result->isSuccess());
76 | } catch (SimpleValidator\SimpleValidatorException $e) {
77 | $this->fail("Exception occured: " . $e->getMessage());
78 | }
79 | return;
80 | }
81 |
82 | public function testValidAndParamStaticMethodRule() {
83 | $rules = array(
84 | 'name' => array(
85 | 'testParamStaticRule(test)'
86 | )
87 | );
88 | try {
89 | $validation_result = CustomValidator::validate(null, $rules);
90 | $this->assertTrue($validation_result->isSuccess());
91 | } catch (SimpleValidator\SimpleValidatorException $e) {
92 | $this->fail("Exception occured: " . $e->getMessage());
93 | }
94 | return;
95 | }
96 |
97 | public function testValidParamButNonStaticMethodRule() {
98 | $rules = array(
99 | 'name' => array(
100 | 'testParamRule(test)'
101 | )
102 | );
103 | try {
104 | CustomValidator::validate(null, $rules);
105 | } catch (SimpleValidator\SimpleValidatorException $e) {
106 | if ($e->getCode() == SimpleValidator\SimpleValidatorException::STATIC_METHOD)
107 | return;
108 | else
109 | $this->fail("Wrong Exception Code: " . $e->getCode());
110 | }
111 | $this->fail("Could not catched Exception");
112 | }
113 |
114 | public function testValidMultipleParams() {
115 | $rules = array(
116 | 'name' => array(
117 | 'multipleParams(1,2,3)'
118 | )
119 | );
120 | $validation = CustomValidator::validate(null, $rules);
121 | $this->assertTrue($validation->isSuccess());
122 | }
123 |
124 | public function testInvalidMultipleParams() {
125 | $rules = array(
126 | 'name' => array(
127 | 'multipleParams(3,2,1)'
128 | )
129 | );
130 | $validation = CustomValidator::validate(null, $rules);
131 | $this->assertFalse($validation->isSuccess());
132 | }
133 |
134 | }
135 |
136 | ?>
137 |
--------------------------------------------------------------------------------
/unit-test/input_name_param.test.php:
--------------------------------------------------------------------------------
1 | rules = array(
7 | 'test1' => array('equals(:test2)')
8 | );
9 | }
10 |
11 | public function testValidInputs() {
12 | $inputs = array(
13 | 'test1' => 'foo',
14 | 'test2' => 'foo'
15 | );
16 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
17 | $this->assertTrue($validation_result->isSuccess());
18 | }
19 |
20 | public function testInvalidInputs() {
21 | $inputs = array(
22 | 'test1' => 'foo',
23 | 'test2' => 'foo2'
24 | );
25 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
26 | $this->assertFalse($validation_result->isSuccess());
27 | }
28 |
29 | public function testNullParameterNameInputs() {
30 | $inputs = array(
31 | 'test1' => 'foo'
32 | );
33 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
34 | $this->assertFalse($validation_result->isSuccess());
35 | }
36 |
37 | public function testEmptyParameterNameInputs() {
38 | $inputs = array(
39 | 'test1' => 'foo',
40 | 'test2' => ''
41 | );
42 | $validation_result = SimpleValidator\Validator::validate($inputs, $this->rules);
43 | $this->assertFalse($validation_result->isSuccess());
44 | }
45 |
46 | }
47 |
48 | ?>
49 |
--------------------------------------------------------------------------------
/unit-test/integer.test.php:
--------------------------------------------------------------------------------
1 | rules = array(
9 | 'test' => array('integer')
10 | );
11 | }
12 |
13 | public function testIntegerInput() {
14 | $inputs = array(
15 | 'test' => 15
16 | );
17 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
18 | $this->assertEquals($validator->isSuccess(), true);
19 | }
20 |
21 | public function testIntegerStringInput() {
22 | $inputs = array(
23 | 'test' => "15"
24 | );
25 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
26 | $this->assertEquals($validator->isSuccess(), true);
27 | }
28 |
29 | public function testFloatInput() {
30 | $inputs = array(
31 | 'test' => 15.5
32 | );
33 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
34 | $this->assertEquals($validator->isSuccess(), false);
35 | }
36 |
37 | public function testStringInput() {
38 | $inputs = array(
39 | 'test' => "test12"
40 | );
41 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
42 | $this->assertEquals($validator->isSuccess(), false);
43 | }
44 |
45 | public function testHexadecimalIntegerInput() {
46 | $inputs = array(
47 | 'test' => 0x1A
48 | );
49 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
50 | $this->assertEquals($validator->isSuccess(), true);
51 | }
52 |
53 | public function testNegativeIntegerInput() {
54 | $inputs = array(
55 | 'test' => -15
56 | );
57 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
58 | $this->assertEquals($validator->isSuccess(), true);
59 | }
60 |
61 | public function testOctalNumberInput() {
62 | $inputs = array(
63 | 'test' => 0123
64 | );
65 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
66 | $this->assertEquals($validator->isSuccess(), true);
67 | }
68 |
69 | public function testVeryBigInput() {
70 | $inputs = array(
71 | 'test' => 9E19
72 | );
73 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
74 | $this->assertEquals($validator->isSuccess(), false);
75 | }
76 |
77 | public function testVerySmallInput() {
78 | $inputs = array(
79 | 'test' => -9E19
80 | );
81 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
82 | $this->assertEquals($validator->isSuccess(), false);
83 | }
84 |
85 | public function testEmptyInput() {
86 | $inputs = array(
87 | 'test' => ''
88 | );
89 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
90 | $this->assertEquals($validator->isSuccess(), false);
91 | }
92 |
93 | public function testNullInput() {
94 | $inputs = array(
95 | 'test' => null
96 | );
97 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
98 | $this->assertEquals($validator->isSuccess(), false);
99 | }
100 |
101 | }
102 |
103 | ?>
104 |
--------------------------------------------------------------------------------
/unit-test/ip.test.php:
--------------------------------------------------------------------------------
1 | rules = array(
7 | 'test' => array('ip')
8 | );
9 | }
10 |
11 | public function tearDown() {
12 |
13 | }
14 |
15 | public function testValidIPv4Input() {
16 | $inputs = array(
17 | 'test' => "89.250.130.65"
18 | );
19 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
20 | $this->assertEquals($validator->isSuccess(), true);
21 | }
22 |
23 | public function testValidFormatInvalidIPInput() {
24 | $inputs = array(
25 | 'test' => "89.300.130.65"
26 | );
27 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
28 | $this->assertEquals($validator->isSuccess(), false);
29 | }
30 |
31 | public function testValidIPv6Input() {
32 | $inputs = array(
33 | 'test' => "2a03:2880:10:1f02:face:b00c::25"
34 | );
35 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
36 | $this->assertEquals($validator->isSuccess(), true);
37 | }
38 |
39 | public function testInvalidFormatInput() {
40 | $inputs = array(
41 | 'test' => "Simple Validator"
42 | );
43 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
44 | $this->assertEquals($validator->isSuccess(), false);
45 | }
46 |
47 | }
48 |
49 | ?>
50 |
--------------------------------------------------------------------------------
/unit-test/multiple_parameter.test.php:
--------------------------------------------------------------------------------
1 | test_data = array(
9 | 'test1' => 'test data 1',
10 | 'test2' => 'test data 2',
11 | 'test3' => 'test data 3'
12 | );
13 | }
14 |
15 | public function testValidValidation() {
16 | $rules = array(
17 | 'test1' => array(
18 | 'rule1(:test2,3,:test3)' => function($input, $test2, $value, $test3) {
19 | if (($input == "test data 1") && ($value == 3) && ($test2 == "test data 2") && ($test3 == "test data 3"))
20 | return true;
21 | return false;
22 | }
23 | )
24 | );
25 | $validation = \SimpleValidator\Validator::validate($this->test_data, $rules);
26 | $this->assertTrue($validation->isSuccess());
27 | }
28 |
29 | public function testInvalidValidation() {
30 | $rules = array(
31 | 'test1' => array(
32 | 'rule1(:test2,3,:test3)' => function($input, $test2, $value, $test3) {
33 | if (($input == "test data 1") && ($value == 3) && ($test2 == "test data 1") && ($test3 == "test data 1"))
34 | return true;
35 | return false;
36 | }
37 | )
38 | );
39 | $naming = array(
40 | 'test2' => 'Test 2'
41 | );
42 | $validation = \SimpleValidator\Validator::validate($this->test_data, $rules, $naming);
43 | $this->assertFalse($validation->isSuccess());
44 | $validation->customErrors(array(
45 | 'rule1' => "Foo :params(0) bar :params(1) baz :params(2)"
46 | ));
47 | $errors = $validation->getErrors();
48 | $this->assertEquals("Foo Test 2 bar 3 baz test3", $errors[0]);
49 | }
50 |
51 | }
52 |
53 | ?>
54 |
--------------------------------------------------------------------------------
/unit-test/required.test.php:
--------------------------------------------------------------------------------
1 | rules = array(
9 | 'test' => array('required')
10 | );
11 | }
12 |
13 | public function tearDown() {
14 |
15 | }
16 |
17 | public function testEmptyInput() {
18 | $inputs = array(
19 | 'test' => ''
20 | );
21 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
22 | $this->assertEquals($validator->isSuccess(), false);
23 | }
24 |
25 | public function testNullInput() {
26 | $inputs = array(
27 | 'test' => null
28 | );
29 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
30 | $this->assertEquals($validator->isSuccess(), false);
31 | }
32 |
33 | public function testOnlyWhiteSpaceInput() {
34 | $inputs = array(
35 | 'test' => ' '
36 | );
37 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
38 | $this->assertEquals($validator->isSuccess(), false);
39 | }
40 |
41 | public function testUnassignedInput() {
42 | $inputs = array();
43 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
44 | $this->assertEquals($validator->isSuccess(), false);
45 | }
46 |
47 | public function testNullInputArray() {
48 | $inputs = null;
49 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
50 | $this->assertEquals($validator->isSuccess(), false);
51 | }
52 |
53 | public function testZeroInput() {
54 | $inputs = array(
55 | 'test' => '0'
56 | );
57 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
58 | $this->assertEquals($validator->isSuccess(), true);
59 | }
60 |
61 | public function testZeroPointZeroInput() {
62 | $inputs = array(
63 | 'test' => 0.0
64 | );
65 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
66 | $this->assertEquals($validator->isSuccess(), true);
67 | }
68 |
69 | }
70 |
71 | ?>
72 |
--------------------------------------------------------------------------------
/unit-test/url.test.php:
--------------------------------------------------------------------------------
1 | rules = array(
7 | 'test' => array('url')
8 | );
9 | }
10 |
11 | public function tearDown() {
12 |
13 | }
14 |
15 | public function testHttpURLInput() {
16 | $inputs = array(
17 | 'test' => "http://www.google.com"
18 | );
19 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
20 | $this->assertEquals($validator->isSuccess(), true);
21 | }
22 |
23 | public function testHttpsURLInput() {
24 | $inputs = array(
25 | 'test' => "https://www.google.com"
26 | );
27 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
28 | $this->assertEquals($validator->isSuccess(), true);
29 | }
30 |
31 | public function testMailtoInput() {
32 | $inputs = array(
33 | 'test' => "mailto:geliscan@gmail.com"
34 | );
35 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
36 | $this->assertEquals($validator->isSuccess(), true);
37 | }
38 |
39 | public function testDomainInput() {
40 | $inputs = array(
41 | 'test' => "www.google.com"
42 | );
43 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
44 | $this->assertEquals($validator->isSuccess(), false);
45 | }
46 |
47 | public function testEmailInput() {
48 | $inputs = array(
49 | 'test' => "geliscan@gmail.com"
50 | );
51 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
52 | $this->assertEquals($validator->isSuccess(), false);
53 | }
54 |
55 | public function testFtpInput() {
56 | $inputs = array(
57 | 'test' => "ftp://ftp.is.co.za.example.org/rfc/rfc1808.txt"
58 | );
59 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
60 | $this->assertEquals($validator->isSuccess(), true);
61 | }
62 |
63 | public function testTelnetInput() {
64 | $inputs = array(
65 | 'test' => "telnet://melvyl.ucop.example.edu/"
66 | );
67 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
68 | $this->assertEquals($validator->isSuccess(), true);
69 | }
70 |
71 | public function testLdapInput() {
72 | $inputs = array(
73 | 'test' => "ldap://[2001:db8::7]/c=GB?objectClass?one"
74 | );
75 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
76 | $this->assertEquals($validator->isSuccess(), true);
77 | }
78 |
79 | /*
80 | public function testPhoneInput() {
81 |
82 | $inputs = array(
83 | 'test' => "tel:+1-816-555-1212"
84 | );
85 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
86 | $this->assertEquals($validator->isSuccess(), true);
87 | }
88 |
89 | public function testUrnInput() {
90 | $inputs = array(
91 | 'test' => "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
92 | );
93 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
94 | $this->assertEquals($validator->isSuccess(), true);
95 | }
96 | */
97 |
98 | public function testAnyStringInput() {
99 | $inputs = array(
100 | 'test' => "simple validator"
101 | );
102 | $validator = SimpleValidator\Validator::validate($inputs, $this->rules);
103 | $this->assertEquals($validator->isSuccess(), false);
104 | }
105 |
106 | }
107 |
108 | ?>
109 |
--------------------------------------------------------------------------------