-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAmslib_Validator.php
1700 lines (1430 loc) · 58.6 KB
/
Amslib_Validator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*******************************************************************************
* Copyright (c) {15/03/2008} {Christopher Thomas}
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contributors/Author:
* {Christopher Thomas} - Creator - [email protected]
*
*******************************************************************************/
/**
* class: Amslib_Validator
*
* group: core
*
* file: Amslib_Validator.php
*
* description: todo, write description
*
* todo: Validates a form posted from the browser to see whether the data conforms to the expected types
*
* future improvements
* - Add a url validator method perhaps?
* - move the required parameter into the options structure
* - Allow a date to validate between two unix timestamps defining the start and end period (useful for birthdates, restriction of dates based on product availability etc)
*/
class Amslib_Validator
{
/**
* number: $errorLimit
*
* The number of errors this object will tolerate before it's going to kill your code stone cold dead
*
* value: 1000
*/
protected $errorLimit = 1000;
/**
* array: $custom
*
* Contains all the custom validator types that are allowed to validate, in order to
* add a new validator you must register it's type in the constructor and provide the callback
*/
protected $custom;
/**
* array: $error
*
* Contains an array of strings which represent data elements which failed to validate
*/
protected $error;
/**
* array: $rules
*
* Contains an array of items to validate from the source data array, the source
* might contain 100 elements, but you only want to validate 20, this is how we know which
* to validate and which to ignore
*/
protected $rules;
/**
* array: $source
*
* The source array of data to validate according to the rules attached to the items
*/
protected $source;
/**
* array: $validData
*
* The data from the source array which was validated correctly, this is wanted usually to refill the form with information
* after a failed validation has occured, to stop the user from having to retype all the form again
*/
protected $validData;
/**
* boolean: $hasExecuted
*
* A toggle to know whether the validator has run or not, sometimes this is wanted to know whether or not to bother obtaining
* information about the status of validation, because it's simple to check whether any validation information retrieved would
* be correct or unnecessary
*/
protected $hasExecuted;
/**
* method: validate_logical_or
*
* This will return the first value which was found from the requested fields, it will stop when one match is found
*
* usage: $v->add("has_file","logical_or",true,array("select_file","csv_file"));
*/
protected function validate_logical_or($name,$value,$required,$options)
{
$valid = $this->getValid();
$keys = array_keys($valid);
foreach($options as $o){
// Make sure the key exists in the array
if(!in_array($o,$keys)) continue;
// If the key is a string, makes sure it's not empty
if(is_string($valid[$o]) && strlen($valid[$o]) == 0) continue;
$this->setValid($name,$valid[$o]);
return true;
}
if(!$required) return true;
$this->setError($name,$value,"LOGICAL_OR_FAILED");
return false;
}
protected function validate_logical_and($name,$value,$required,$options)
{
$valid = $this->getValid();
$keys = array_keys($valid);
$data = array();
foreach($options as $o){
// Make sure the key exists in the array
$exists = in_array($o,$keys);
// Make sure it's not empty
$empty = is_string($valid[$o]) && strlen($valid[$o]) == 0;
if(!$exists || !$empty){
if(!$required) return true;
$this->setError($name,$value,"LOGICAL_AND_FAILED");
return true;
}
$data[$o] = $valid[$o];
}
$this->setValid($name,$data);
return true;
}
/**
* method: validate_array
*
* todo: write documentation
*/
protected function validate_array($name,$value,$required,$options)
{
$error = false;
if(!isset($options["type"])) $error = "ARRAY_REQUIRE_TYPE_PARAM";
if(!is_array($value)) $error = "ARRAY_INVALID";
if($error === false){
$arrayValidator = new self($value);
foreach($value as $k=>$v){
$arrayValidator->add($k,$options["type"],$required,$options);
}
$data = array(
"success" => $arrayValidator->execute(),
"valid" => $arrayValidator->getValid(),
"errors" => $arrayValidator->getErrors()
);
if(!isset($options["optimise"]) || !$options["optimise"]){
$data = $data["valid"];
}
}
if($required == true && $error !== false) return $error;
if($error === false) $this->setValid($name,$data);
return true;
}
protected function validate_json($name,$value,$required,$options)
{
$error = false;
if(!is_string($value)) $error = "JSON_INVALID";
if(!strlen($value) && !isset($options["allow_empty"])) $error = "JSON_EMPTY";
try{
$value = json_decode($value,true);
if(!is_array($value)) $error = "JSON_INVALID";
}catch(Exception $e){
$error = "JSON_INVALID";
}
if($required == true && $error !== false) return $error;
if($error === false) $this->setValid($name,$value);
return true;
}
/**
* method: isbn
*
* todo: write documentation
*/
protected function validate_isbn($name,$value,$required,$options)
{
// strip out some characters we know might be present, but have to be removed
$options["original_value"] = $value;
$value = str_replace(array("isbn","-"," ",".",","),"",strtolower($value));
if(is_string($value)){
if(strlen($value) == 10) return $this->validate_isbn10($name,$value,$required,$options);
if(strlen($value) == 13) return $this->validate_isbn13($name,$value,$required,$options);
if($required) return "ISBN_INVALID";
}
if($required) return "ISBN_NOT_STRING";
return true;
}
/**
* method: isbn10
*
* todo: write documentation
*/
protected function validate_isbn10($name,$value,$required,$options)
{
// Disclaimer, I took this code from the isbn wikipedia article
$check = 0;
for ($i = 0; $i < 9; $i++) $check += (10 - $i) * substr($value, $i, 1);
$t = substr($value, 9, 1); // tenth digit (aka checksum or check digit)
$check += ($t == 'x' || $t == 'X') ? 10 : $t;
if($check % 11 == 0) $this->setValid($name,$options["original_value"]);
else if($required) return "ISBN_10_INVALID";
return true;
}
/**
* method: isbn13
*
* todo: write documentation
*/
protected function validate_isbn13($name,$value,$required,$options)
{
// Disclaimer, I took this code from the isbn wikipedia article
$check = 0;
for ($i = 0; $i < 13; $i+=2) $check += substr($value, $i, 1);
for ($i = 1; $i < 12; $i+=2) $check += 3 * substr($value, $i, 1);
if($check % 10 == 0) $this->setValid($name,$options["original_value"]);
else if($required) return "ISBN_13_INVALID";
return true;
}
/**
* method: text
*
* Validate a text field using the information passed to it
*
* parameters:
* name - The name of the field
* value - The value of the field
* required - Boolean true or false whether the field is mandatory or not
* options - Validation restrictions: minlength,maxlength
*
* returns:
* If failed with the string length is zero and required being enabled, return "TEXT_LENGTH_ZERO"
* If failed with string length being below minimum length, return "TEXT_LENGTH_IS_BELOW_MINIMUM"
* If failed with string length being above maximum length, return "TEXT_LENGTH_IS_ABOVE_MAXIMUM"
* If successful, will return true and assign the valid data into the $validData array for retrieval later
*
* operations:
* - Find the length of the string
* - If the length of the string is zero, but required, return VALIDATOR_TEXT_LENGTH_ZERO
* - If the length of the string is below the minimum set, return VALIDATOR_TEXT_LENGTH_IS_BELOW_MINIMUM
* - If the length of the string is above the maximum set, return VALIDATOR_TEXT_LENGTH_IS_ABOVE_MAXIMUM
* - else the validation passed, move to setting the validData
* - if successfully validated Set the validData item for this method
*
* notes:
* - we should create a shared method for doing simple calculations, like "checkLength" to see whether the value passes this test or not
*/
protected function validate_text($name,$value,$required,$options)
{
$len = strlen(trim($value));
$error = false;
// replace this key with a better named version, but have this code here to patch over code which uses it
if(array_key_exists("permit-empty",$options)){
Amslib_Debug::log("**** DEPRECATED CODE: permit-empty flag detected","stack-trace");
$options["allow-empty"] = $options["permit-empty"];
}
if($len == 0 && !isset($options["allow-empty"])){
$error = "TEXT_LENGTH_ZERO";
}
if(isset($options["minlength"]) && $len < $options["minlength"]){
$error = "TEXT_LENGTH_IS_BELOW_MINIMUM";
}
if(isset($options["maxlength"]) && $len > $options["maxlength"]){
$error = "TEXT_LENGTH_IS_ABOVE_MAXIMUM";
}
if(isset($options["limit-input"]) && !in_array($value,$options["limit-input"])){
$error = "TEXT_CANNOT_MATCH_AGAINST_LIMIT";
}
// NOTE: maybe "invalid" should change to "exclude-input" to be closer to the syntax of "limit-input" ?
if(isset($options["invalid"])){
if(!is_array($options["invalid"])){
$options["invalid"] = array($options["invalid"]);
}
if(in_array($value,$options["invalid"])){
$error = "TEXT_INVALID_INPUT";
}
}
if($required == true && $error !== false) return $error;
if($error === false) $this->setValid($name,$value);
return true;
}
/**
* method: validate_alpha
*
* Validate a text field contains only alphabetical (A-Za-z) characters
*
* parameters:
* name - The name of the field
* value - The value of the field
* required - Boolean true or false whether the field is mandatory or not
* options - Validation restrictions: minlength,maxlength
*
* returns:
* If failed, will return a text string representing the error (this can be used to represent a language translation key)
* If successful, will return true and assign the valid data into the $validData array for retrieval later
*
* operations:
* - Otherwise, validate as a alphabetical string only
* - If success, validation passed, set the validData to store the data and return true
*/
protected function validate_alpha($name,$value,$required,$options)
{
$status = $this->validate_text($name,$value,$required,$options);
// Text validation failed, drop out here
if($status !== true) return $status;
if(!ctype_alpha($value)) return "TEXT_NOT_ALPHABETICAL";
$this->setValid($name,$value);
return true;
}
/**
* method: validate_alpha_relaxed
*
* Validate a text field contains alphabetical (A-Za-z) characters and some other normal human text characters
*
* parameters:
* name - The name of the field
* value - The value of the field
* required - Boolean true or false whether the field is mandatory or not
* options - Validation restrictions: minlength,maxlength
*
* returns:
* If failed, will return a text string representing the error (this can be used to represent a language translation key)
* If successful, will return true and assign the valid data into the $validData array for retrieval later
*/
protected function validate_alpha_relaxed($name,$value,$required,$options)
{
$status = $this->validate_text($name,$value,$required,$options);
// Text validation failed, drop out here
if($status !== true) return $status;
$regexp = preg_match("/[\p{N}\p{P}\p{S}]/i",$value);
if($regexp != 0) return "TEXT_NOT_ALPHABETICAL";
$this->setValid($name,$value);
return true;
}
/**
* method: validate_password
*
* todo: write documentation
*/
protected function validate_password($name,$value,$required,$options)
{
if(isset($options["p1"]) && isset($options["p2"])){
$f1 = $options["p1"];
$f2 = $options["p2"];
// Are the fields even available? If not, there is an error
if((!isset($this->source[$f1]) || !isset($this->source[$f2]))){
if($required) return "PASSWORD_FIELDS_MISSING";
return true;
}
$p1 = $this->source[$f1];
$p2 = $this->source[$f2];
// If strings are not identical, there is an error
if($p1 != $p2){
// password is not required, so just return true or "NO_MATCH" if required is true
if(!$required) return true;
$this->setError($f1,$p1,"PASSWORDS_NO_MATCH");
$this->setError($f2,$p2,"PASSWORDS_NO_MATCH");
return "PASSWORDS_NO_MATCH";
}
// If the password is empty, there is an error
if(strlen($p1) == 0){
// password is not required, so just return true or "EMPTY" if required is true
if(!$required) return true;
return "PASSWORDS_EMPTY";
}
// Make the password to test through the text validator equal to one of the fields
$value = $p1;
}
return $this->validate_text($name,$value,$required,$options);
}
/**
* method: validate_dni
*
* Validate a Spanish DNI number. DNI is not the 100% correct technical name for this, but it's hard to give a name
* to it since some people call it DNI or others NIF/CIF, it was decided to call it DNI because it made the most sense,
* however imperfect. A DNI number is a identification number for either a spanish national (NIF) a spanish company (CIF)
* or a foreigner (NIE)
*
* parameters:
* name - The name of the field
* $code - The value of the field
* required - Boolean true or false whether the field is mandatory or not
* options - Validation restrictions
*
* returns:
* If code does not match any DNI like profile, will return "DNI_INVALID"
* If code does match, look for nif, cif or nie for the return information, it completely delegates everything
*
* returns:
* Will set the valid value, or return VALIDATOR_DNI_INVALID for a invalid code
*/
protected function validate_dni($name,$code,$required,$options)
{
$code = strtoupper($code);
if(preg_match("/[a-wyz][0-9]{7}[0-9a-z]/i",$code)){
return $this->validate_cif($name,$code,$required,$options);
}
if(preg_match("/[x][0-9]{7,8}[a-z]/i",$code)){
return $this->validate_nie($name,$code,$required,$options);
}
if(preg_match("/[0-9]{8}[a-z]/i",$code)){
return $this->validate_nif($name,$code,$required,$options);
}
if(!$required) return true;
return "DNI_INVALID";
}
/**
* function: validate_nif
*
* Validate a Spanish NIF identication code
*
* parameters:
* $code - The NIF DNI code to check
*
* returns:
* If failed because the end character did not match the correct calculated one, return "NIF_INVALID
* If failed because the last letter was not a alpha character, return "NIF_ENDCHAR_NOT_ALPHA"
* If successful, will set the valid data array and return true
*
* operations:
* - Check the end character is a letter
* - obtain the numerical part and modulus against 23
* - The result, will be an array index into a list of validation characters
* - If the end letter from the dni was the same letter as the validation character then the DNI is valid
*/
protected function validate_nif($name,$code,$required,$options)
{
$letter = substr($code,strlen($code)-1);
$numbers = intval(substr($code,0,-1));
if(is_numeric($numbers) && !is_numeric($letter)){
$source = "TRWAGMYFPDXBNJZSQVHLCKET";
if($letter != $source[$numbers%23]) return "NIF_INVALID";
$this->setValid($name,$code);
return true;
}
if(!$required) return true;
return "NIF_ENDCHAR_NOT_ALPHA";
}
/**
* function: validate_cif
*
* Validate a Spanish CIF identification code
*
* parameters:
* $code - The CIF to check
*
* returns:
* If failed, will return a string "CIF_INVALID"
* If successful, will set the valid data array and return true
*
* operations:
* - grab the last value, this is the checksum value
* - sum all the odd numbers together
* - double each even number and if above 9, add both digits together like the luhn algoritum [15 -> 6 (1+5)] and add the result to the sum
* - obtain the modulus of the resulting sum as the control (obtain the modulus of the that as well (in case of sum = 10)
* - If the control equals the last value, or the letter at that index, then return positively, otherwise, failure
*/
protected function validate_cif($name,$code,$required,$options)
{
$lastLetter = array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I");
$numbers = substr($code,1);
$last = substr($numbers,strlen($numbers)-1);
$sum = 0;
// Sum up all the even numbers
for($pos=1;$pos<7;$pos+=2){
$sum += (int)(substr($numbers,$pos,1));
}
// Sum up all the odd numbers (but differently)
// This uses the Luhn Algorithm:
// Any value greater than 10, comprises two numbers (etc: 15 is [1, 5] )
// Add both together, this is the value to sum
for($pos=0;$pos<8;$pos+=2){
$val = 2*(int)(substr($numbers,$pos,1));
$val = str_pad($val,2,"0",STR_PAD_LEFT);
$sum += (int)$val[0]+(int)$val[1];
}
// Obtain the modulus of 10 and subtract it from 10, if the sum was 10, control is 0 (second modulus)
$control = (10 - ($sum % 10)) % 10;
if(($last == $control) || ($last == $lastLetter[$control])){
$this->setValid($name,$code);
return true;
}
if(!$required) return true;
return "CIF_INVALID";
}
/**
* function: validate_nie
*
* Validate a Spanish NIE identification code
*
* parameters:
* $code - The NIE DNI code to check
*
* returns:
* If failed, will return a string "NIE_INVALID"
* If successful, will set the valid data array and return true
*
* notes:
* - This is a proxy method for validateNIF, which is identical in calculation, except we need to remove the
* X from the front of the NIE and then check the remaining string (which is a valid NIE, or should be)
*/
protected function validate_nie($name,$code,$required,$options)
{
$firstCharacter = substr($code,0,1);
if($firstCharacter == "X"){
$nif = substr($code,1);
if($this->validate_nif($name,$nif,$required,$options) === true){
$this->setValid($name,$code);
return true;
}
}
if(!$required) return true;
return "NIE_INVALID";
}
/**
* method: validate_boolean
*
* Validate a boolean value that is correctly representing a boolean value (and not a string such as "1998")
*
* parameters:
* name - The name of the field
* value - The value of the field
* required - Boolean true or false whether the field is mandatory or not
* options - Validation restrictions
*
* returns:
* If failed, will return a string "BOOLEAN_INVALID"
* If successful, will set the validData array and return true
*
* operations:
* - if string, lower case it
* - if numeric, cast to bool
* - test value against some known values that normally mean "true", return true or false, depends on whether it successfully matches or not
* - if value was not required to succeed validation, just return true
* - if value was boolean then if the test was not delegated assign the value to the validData array and return true
* - if value was not boolean, return VALIDATOR_BOOLEAN_INVALID
*
* carlos seez:
* - Please find your boolean validation method replaced by something else that has little resemblance to the previous description, but that actually works, even if it's a bit eager to flag something as false.
* chris reply: thanks for fixing it! I didnt realise it would do that
* chris seez: I changed it again, it seems that the version was returning invalid when it found boolean false :)
*/
protected function validate_boolean($name,$value,$required,$options)
{
$error = false;
$true = array(1,"1",true,"true","on","yes");
$false = array(0,"0",false,"false","off","no","");
if($value == NULL && !isset($options["ignorenull"])){
$error = "BOOLEAN_IS_NULL";
}
$value = strtolower($value);
if(!in_array($value,array_merge($true,$false))){
$error = "BOOLEAN_INVALID";
}
$bool = !!in_array($value,$true,true);
if(isset($options["limit-input"]) && !in_array($bool,$options["limit-input"])){
$error = "BOOLEAN_CANNOT_MATCH_AGAINST_LIMIT_INPUT";
}else if(isset($options["limit-output"]) && !in_array($bool,$options["limit-output"])){
$error = "BOOLEAN_CANNOT_MATCH_AGAINST_LIMIT_OUTPUT";
}
// If there was an error, if you require a valid value, return error, otherwise, true
if($error !== false){
return $required ? $error : true;
}
$this->setValid($name,$bool);
return true;
}
/**
* method: validate_number
*
* Validate a numerical value
*
* parameters:
* name - The name of the field
* value - The value of the field
* required - Boolean true or false, whether the field is mandatory or not
* options - Validation restrictions: minvalue, maxvalue
*
* returns:
* If failed to validate because value is NULL, will return string "NUMBER_IS_NULL"
* If failed to validate because value is NaN (like "abcdef"), will return string "NUMBER_IS_NAN"
* If failed to validate because value is below minimum value will return string "NUMBER_IS_BELOW_MINIMUM"
* If failed to validate because value is above maximum value will return string "NUMBER_IS_ABOVE_MAXIMUM"
* If failed to validate because value is not in the limited input options will return string "NUMBER_CANNOT MATCH AGAINST LIMIT"
* If failed to validate because value is not the required length of characters will return string "NUMBER_CANNOT_MATCH_LENGTH"
* If failed to validate because value is shorter than required length of characters will return string "NUMBER_CANNOT_MATCH_MINLENGTH"
* If failed to validate because value is longer than required length of characters will return string "NUMBER_CANNOT_MATCH_MAXLENGTH"
* If successful, will set the data into the valid data array and return true
*
* operations:
* - use is_numeric to test whether value is a number or not
* - if required is true, but is_numeric returns false, error occurred
* - If value is NaN, return NAN error
* - If value is null, return NULL error
* - If value is not in limit inputs array of allowed values, return limit error
* - If value is not the required number of characters, return length error
* - If value is shorter or shorter than the required number of characters, return min or max length error
* - If value is above or below value restrictions, return a "below" or "above" error
* - else set the validData array and return true
*
*/
protected function validate_number($name,$value,$required,$options)
{
$error = false;
if($value === NULL && !isset($options["ignorenull"])){
$error = "NUMBER_IS_NULL";
}
if(!is_numeric($value)){
$error = "NUMBER_NAN";
}
if(isset($options["minvalue"]) && is_numeric($options["minvalue"])){
if($value < $options["minvalue"]) $error = "NUMBER_IS_BELOW_MINIMUM";
}
if(isset($options["maxvalue"]) && is_numeric($options["maxvalue"])){
if($value > $options["maxvalue"]) $error = "NUMBER_IS_ABOVE_MAXIMUM";
}
// TODO: modify this code so it will allow setting the limit-input as a single value and not ONLY as an array
if(isset($options["limit-input"]) && !in_array($value,$options["limit-input"])){
$error = "NUMBER_CANNOT_MATCH_AGAINST_LIMIT";
}
if(isset($options["length"]) && is_numeric($options["length"])){
if(!strlen($value) != $options["length"]) $error = "NUMBER_CANNOT_MATCH_LENGTH";
}
if(isset($options["minlength"]) && is_numeric($options["minlength"])){
if(!strlen($value) < $options["minlength"]) $error = "NUMBER_CANNOT_MATCH_MINLENGTH";
}
if(isset($options["maxlength"]) && is_numeric($options["maxlength"])){
if(!strlen($value) > $options["maxlength"]) $error = "NUMBER_CANNOT_MATCH_MAXLENGTH";
}
// If there was an error, if you require a valid value, return error, otherwise, true
if($error !== false){
return ($required) ? $error : true;
}
$this->setValid($name,$value);
return true;
}
/**
* method: validate_email
*
* Validate a string against an email template, if the value matches the pattern, will validate successfully
*
* parameters:
* name - The name of the field
* value - The value of the field
* required - Boolean true or false, whether the field is mandatory or not
* options - Validation restrictions
*
* returns:
* If failed because string was empty, will return "EMAIL_EMPTY"
* If failed because pattern did not match, will return "EMAIL_INVALID"
* If successful, will set validData and return true
*
* operations:
* - Test email string length, if zero and required is true, return "EMAIL_EMPTY"
* - Trim the resulting non-empty string from whitespace before and after
* - Match the string against the pattern which describes a valid email (perhaps not ALL possible valid emails, but 99% at least)
* - If matches, set the validData and return true
* - If failed, but required is NOT true, return true anyway
* - If required, but failed all tests, return "EMAIL_INVALID"
*/
protected function validate_email($name,$value,$required,$options)
{
$error = false;
$value = trim($value);
if(strlen($value) == 0 && $required == true) $error = "EMAIL_EMPTY";
if(isset($options["invalid"]) && in_array($value,$options["invalid"])) $error = "EMAIL_INVALID_INPUT";
if(!is_email($value)) $error = "EMAIL_INVALID";
if($required == true && $error !== false) return $error;
if($error === false) $this->setValid($name,$value);
return true;
}
/**
* method: validate_domain
*
* Validate a domain name by performing a DNS lookup on the given information
*
* parameters:
* name - The name of the field
* value - The value of the field (domain name)
* required - Boolean true or false, whether the field is mandatory or not
* options - Validation restrictions
*
* returns:
* If domain name was an empty string, will return "DOMAIN_EMPTY"
* If domain was invalid (or no response) will return "DOMAIN_INVALID"
* If successful, will set validData and return true
*
* notes:
* - It is possible that this method will fail with VALID domains, because they do not respond in time
* - This method required a DNS lookup, which might be expensive if performed lots of times.
*/
protected function validate_domain($name,$value,$required,$options)
{
$value = trim($value);
if(strlen($value) == 0 && $required == true) return "DOMAIN_EMPTY";
$record = dns_get_record($value);
if($record){
$this->setValid($name,$value);
return true;
}
if($required == false) return true;
return "DOMAIN_INVALID";
}
/**
* method: validate_ip_address
*
* Validate an ip address by using ip2long to convert it and detect false for failure
*
* parameters:
* name - The name of the field
* value - The value of the field (ip address)
* required - Boolean true or false, whether the field is mandatory or not
* options - Validation restrictions
*
* returns:
* - If ip address name was an empty string, will return "IP_ADDRESS_EMPTY"
* - If ip address was invalid will return "IP_ADDRESS_INVALID"
* - If successful, will set valid data and return true
*/
protected function validate_ip_address($name,$value,$required,$options)
{
$value = trim($value);
if(strlen($value) == 0 && $required == true) return "IP_ADDRESS_EMPTY";
$record = ip2long($value) !== false;
if($record){
$this->setValid($name,$value);
return true;
}
if($required == false) return true;
return "IP_ADDRESS_INVALID";
}
/**
* method: validate_phone
*
* Validate a phone number
*
* parameters:
* name - The name of the field
* value - The value of the field
* required - Boolean true or false, whether the field is mandatory or not
* options - Validation restrictions: minlength
*
* returns:
* If failed because string was empty, but required, return "PHONE_EMPTY"
* If failed because string was less than minimum length, return "PHONE_LENGTH_INVALID"
* If failed because it did not match pattern required, return "PHONE_INVALID"
*
* operations:
* - Test email string length, if zero and required is true, return "PHONE_EMPTY"
* - remove all typical non-numeric characters from phone numbers (like brackets, +, -, " " and periods and commas)
* - if the length of the string is less than the minimum, return "PHONE_LENGTH_INVALID"
* - Remove all numerical characters with nothing (removing all numerical characters means we can see how many NON numerical characters there are)
* - trim the result
* - If the string length is NOT zero, it means that alphabetical characters are found, like abcddef, etc, this is invalid, we should only have numerical characters in the string
* - if the string length was zero, we contained a minimum length string, that only contained numerical characters, this is valid, set the validData and return true
*/
protected function validate_phone($name,$value,$required,$options)
{
$error = false;
if(strlen($value)){
$temp = str_replace("(","",$value);
$temp = str_replace(")","",$temp);
$temp = str_replace("+","",$temp);
$temp = str_replace("-","",$temp);
$temp = str_replace(" ","",$temp);
$temp = str_replace(".","",$temp);
$temp = str_replace(",","",$temp);
if(isset($options["minlength"]) && strlen($temp) < $options["minlength"]){
$error = "PHONE_LENGTH_INVALID";
}
if($error == false){
$temp = preg_replace("/\d/","",$temp);
$temp = trim($temp);
if(strlen($temp)) $error = "PHONE_INVALID";
}
}else if(empty($options["allow_empty"])){
$error = "PHONE_EMPTY";
}
// If there was an error
if($error !== false)
{
// If you require the number to be valid, return the error
// If you don't require a valid number, just return true
return ($required) ? $error : true;
}
$this->setValid($name,$value);
return true;
}
/**
* method: validate_date
*
* Very simple method to convert a data to a UNIX timestamp using strtotime
*
* parameters:
* name - The name of the field
* value - The value of the field
* required - Boolean true or false, whether the field is mandatory or not
* options - Validation restrictions
*
* returns:
* Boolean true is required AND success were both true
* Boolean true is required was false
* Boolean false if one of those conditions is not supported
*/
protected function validate_date($name,$value,$required,$options)
{
// If a numeric field is asked to validate against a date, it'll first be
// converted assuming it's a unix timestamp normally I dislike the idea of
// validators manipulating their data, but in this case, I think it makes sense
// to allow this exception
if(is_numeric($value)){
if(isset($options["has_milliseconds"])) $value /= 1000;
$format = isset($options["format"]) ? $options["format"] : "Y/m/d H:i:s";
$value = date($format,$value);
}
if(isset($options["format"]) && $options["format"] = "d/m/Y"){
// this idea hasn't been fully tested yet and sometimes fails, so it's disabled for now
//sscanf($value,"%d/%d/%d")
$success = strtotime($value);
}else{
$success = strtotime($value);
}
if($required && $success || !$required){
$this->setValid($name,$value);
return true;
}