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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
|
NAME:
SmartyValidate: a class/plugin for validating form variables
within the Smarty template environment.
AUTHOR:
Monte Ohrt (monte [AT] ohrt [DOT] com)
VERSION:
3.0.3
NOTE: As of version 3.0, SmartyValidate requires Smarty 3.0 or higher.
DATE:
December 12th, 2011
WEBSITE:
http://www.phpinsider.com/php/code/SmartyValidate/
DOWNLOAD:
http://www.phpinsider.com/php/code/SmartyValidate/SmartyValidate-current.tar.gz
SYNOPSIS:
index.php
---------
session_start();
require('Smarty.class.php');
require('SmartyValidate.class.php');
$smarty =& new Smarty;
if(empty($_POST)) {
SmartyValidate::connect($smarty, true);
SmartyValidate::register_validator('fname','FullName','notEmpty');
SmartyValidate::register_validator('fdate','Date','isDate');
$smarty->display('form.tpl');
} else {
SmartyValidate::connect($smarty);
// validate after a POST
if(SmartyValidate::is_valid($_POST)) {
// no errors, done with SmartyValidate
SmartyValidate::disconnect();
$smarty->display('success.tpl');
} else {
// error, redraw the form
$smarty->assign($_POST);
$smarty->display('form.tpl');
}
}
form.tpl
--------
<form method="POST" action="index.php">
{validate id="fname" message="Full Name cannot be empty"}
Full Name: <input type="text" name="FullName">
{validate id="fdate" message="Date is not valid"}
Date: <input type="text" name="Date">
<input type="submit">
</form>
DESCRIPTION:
What is SmartyValidate?
SmartyValidate is a form validation class. Its design goals are to
leverage the Smarty templating environment and make form validation
as easy and flexible as possible.
BACKGROUND:
Form validation is one of the most frequently performed tasks when
it comes to web application programming. Developing form validation
can be a tedious and time consuming task. SmartyValidate simplifies
this effort by abstracting the validation process. You basically
provide the validation criteria and error messages, SmartyValidate
does the rest!
On the application side, you call SmartyValidate::connect($smarty) first,
passing your smarty object as the parameter. Then you register your
validators with the SmartyValidate::register_validator() function, once for
each validation criteria on the form. Once the form is posted, you call
SmartyValidate::is_valid($_POST) and depending on the outcome, you either
continue with a valid form or begin a form redraw cycle until all the
validation criteria is met. This keeps the form validation process to a bare
minimum on the application side.
In the form template, you put {validate ...} tags which handle error
messages that get displayed upon a validation error.
FEATURES:
Supplied validation criteria includes empty, integer, float, price,
email syntax, credit card checksums, credit card exp dates, valid
date syntax, equality between fields, ranges, lengths, regular expression
matching and custom function calls. Create your own through Smarty plugins,
PHP functions or class methods.
Transform functions can be applied to form values prior to validation,
such as trimming, upper-casing, etc. Create your own through Smarty Plugins,
PHP functions or class methods.
{validate ...} tags can be located anywhere in your template, regardless of
where the corresponding fields are located.
Multiple validators may be used for one field. Once one validator fails,
the remaining validators for that field are ignored. A "halt" parameter can
also stop validation on remaining fields.
CAVEATS:
Smarty supports validation on single-level array values such as foo[] and
foo[bar], but does not (currently) support nested array validation such as
foo[bar][blah]. So you can do this:
{validate field="foo[bar]" criteria="notEmpty" ...}
<input type="text" name="foo[bar]">
But not this:
{validate field="foo[bar][blah]" criteria="notEmpty" ...}
<input type="text" name="foo[bar][blah]">
REQUIREMENTS:
You must enable session management prior to using SmartyValidate. Do this
by calling session_start() at the top of your PHP application.
SmartyValidate also requires the Smarty template environment.
INSTALLATION:
It is assumed that you are familiar with the Smarty templating
installation and setup, so I will not explain Smarty template
directories and such. Please refer to the Smarty documentation for
that information.
To install SmartyValidate:
* Copy the 'SmartyValidate.class.php' file to a place within your
php_include path (or use absolute pathnames when including.)
* Copy all of the plugins to your Smarty plugin directory. (located
in the plugins/ directory of the distribution.)
EXAMPLE:
Here is a full working example of how to use SmartyValidate. Put the
form.tpl and success.tpl files in your Smarty template directory.
index.php
---------
<?php
session_start();
// you will need to setup Smarty if
// the defaults are not correct.
require('Smarty.class.php');
require('SmartyValidate.class.php');
$smarty =& new Smarty;
if(empty($_POST)) {
// new form, we (re)set the session data
SmartyValidate::connect($smarty, true);
// register our validators
SmartyValidate::register_validator('fullname', 'FullName', 'notEmpty',
false, false, 'trim');
SmartyValidate::register_validator('phone', 'Phone', 'isNumber', true,
false, 'trim');
SmartyValidate::register_validator('expdate', 'CCExpDate', 'notEmpty',
false, false, 'trim');
SmartyValidate::register_validator('email', 'Email', 'isEmail', false,
false, 'trim');
SmartyValidate::register_validator('date', 'Date', 'isDate', true,
false, 'trim');
SmartyValidate::register_validator('password', 'password:password2', 'isEqual');
// display form
$smarty->display('form.tpl');
} else {
// validate after a POST
SmartyValidate::connect($smarty);
if(SmartyValidate::is_valid($_POST)) {
// no errors, done with SmartyValidate
SmartyValidate::disconnect();
$smarty->display('success.tpl');
} else {
// error, redraw the form
$smarty->assign($_POST);
$smarty->display('form.tpl');
}
}
?>
form.tpl
--------
<form method="post" action="index.php">
{validate id="fullname" message="Full Name Cannot Be Empty"}
Full Name: <input type="text" name="FullName" value="{$FullName|escape}"><br />
{validate id="phone" message="Phone Number Must be a Number"}
Phone :<input type="text" name="Phone" value="{$Phone|escape}" empty="yes"><br />
{validate id="expdate" message="Exp Date not valid"}
Exp Date: <input type="text" name="CCExpDate" size="8" value="{$CCExpDate|escape}"><br />
{validate id="email" message="Email not valid"}
Email: <input type="text" name="Email" size="30" value="{$Email|escape}"><br />
{validate id="date" message="Date not valid"}
Date: <input type="text" name="Date" size="10" value="{$Date|escape}"><br />
{validate id="password" message="passwords do not match"}
password: <input type="password" name="password" size="10" value="{$password|escape}"><br />
password2: <input type="password" name="password2" size="10" value="{$password2|escape}"><br />
<input type="submit">
</form>
success.tpl
-----------
Your form submission succeeded.
PUBLIC METHODS:
function connect(&$smarty, $reset = false)
------------------------------------------
examples:
SmartyValidate::connect($smarty);
SmartyValidate::connect($smarty, true);
connect() is required on every invocation of SmartyValidate. Pass your
$smarty object as the parameter. This sets up SmartyValidate with $smarty
and auto-registers the default form. Passing the optional second param as
true, the default form registration will get reset.
function disconnect()
---------------------
examples:
SmartyValidate::disconnect();
SmartyValidate::disconnect(true);
This clears the SmartyValidate session data for the current form. Call
this after you are completely finished with the SmartyValidate form.
(eg. do NOT call between posts to the same form.) A parameter of true
will force all forms to reset.
function set_form($form_name)
-----------------------------
examples:
SmartyValidate::set_form('myfoo');
This sets the form name for the current session. Setting this omits the
need to supply this formname to other functions thereafter.
function register_object($obj_name,&$object)
--------------------------------------------
examples:
SmartyValidate::register_object('myobj',$myobj);
Register an object with SmartyValidate for use with transform and criteria
functions. Typically do this right after issuing connect(). See the
register_criteria() method for more details.
function is_registered_object($obj_name)
----------------------------------------
examples:
if(!SmartyValidate::is_registered_object('myobj')) { ... do something ... }
Test if an object has been registered.
function register_form($form, $reset = false)
---------------------------------------------
examples:
SmartyValidate::register_form('myform');
SmartyValidate::register_form('myform', true);
Register a form to be validated. Each form must be registered before it can
be validated. You do not have to register the 'default' form, that is done
automatically by SmartyValidate. If you register a form that is already
registered, nothing will happen (returns false). If you have the optional
reset parameter set to true, the form will get reset (essentially
unregistering and reregistering the form.)
function is_registered_form($form)
----------------------------------
examples:
if(!SmartyValidate::is_registered_form('myform')) { ... do something ... }
Test if a form has been registered for validation.
function is_valid(&$formvars, $form = 'default')
------------------------------------------------
examples:
SmartyValidate::is_valid($_POST);
SmartyValidate::is_valid($_POST, 'myform');
Tests if the current form is valid. You MUST supply the form variable array
to this function, typically $_POST. You can optionally pass a form name as
the second parameter, otherwise the 'default' form is used. Call this after
the form is submitted.
function register_criteria($name, $func_name, $form = 'default')
----------------------------------------------------------------
examples:
SmartyValidate::register_criteria('isPass', 'test_password');
SmartyValidate::register_criteria('isPass', 'test_password','myform');
SmartyValidate::register_criteria('isPass', 'myobj::test_password');
SmartyValidate::register_criteria('isPass', 'myobj->test_password');
Registers a new criteria function. All functions must be registered before
they can be used (or exist as a plugin.) You can optionally pass a form
name in the case you are not using the 'default' form. Static method calls
are also supported such as foo::bar. You can also register a method of an
object instance such as foo->bar, but you must first register the object
with SmartyValidate. See the register_object() method. Then use your new
criteria within the template:
{validate field="Password" criteria="isPass" ... }
Note: the "isCustom" criteria type is no longer supported (or necessary.)
See the "BUILDING YOUR OWN" section.
function is_registered_criteria($func_name, $form = 'default')
--------------------------------------------------------------
examples:
if(SmartyValidate::is_registered_criteria('isPass')) { ... }
Tests to see if a criteria function has been registered.
function register_transform($name, $func_name, $form = 'default')
-----------------------------------------------------------------
examples:
function my_upper($value, $params, &$formvars) {
return strtoupper($value);
}
SmartyValidate::register_transform('upper','my_upper');
SmartyValidate::register_transform('upper','my_upper','myform');
Registers a function to use with "transform" parameter. All functions must
be registered before they can be used (or exist as a plugin.) You can
optinally pass a form name in the case you are not using the 'default'
form. 'trim' is already registered (via plugins) by default.
function is_registered_transform($func_name, $form = 'default')
---------------------------------------------------------------
examples:
if(SmartyValidate::is_registered_transform('upper')) { ... }
Tests to see if a transform function has been registered.
function register_validator($id, $field, $criteria, $empty = false, $halt =
false, $transform = null, $form = 'default')
---------------------------------------------------------------------------
examples:
SmartyValidate::register_validator('fullname', 'FullName', 'notEmpty');
SmartyValidate::register_validator('fullname', 'FullName', 'notEmpty', true);
SmartyValidate::register_validator('fullname', 'FullName', 'notEmpty', true,
false, 'trim', 'myform');
Register a validator with the form. You must register at least one
validator. If you specify multiple fields, separate them with a colon and
they will be passed into the validator as params field2, field3, etc.
Example:
SmartyValidate::register_validator('passcheck', 'pass1:pass2', 'isEqual');
{validator id="passcheck" message="your passwords must match"}
function set_page($page, $form = 'default')
---------------------------------------------------------------
examples:
SmartyValidate::set_page('1'));
When doing multi-page forms, this value must be set proir to drawing each
page. Each validator must have a page="1" attribute for the given page.
SMARTYVALIDATE TEMPLATE VARS:
For each form, the variable {$validate.formname.is_error} is a boolean set
to true or false indicating whether the form had any failed validators from
the last is_valid() call. is_error is initialized to "false". The default
form is denoted as {$validate.default.is_error}.
SMARTYVALIDATE FUNCTION SYNTAX:
The basic syntax of the {validate ...} function is as follows:
{validate field="foo" criteria="isNumber" message="foo must be a number"}
Those are the three required attributes to a {validate ...}
function call. "field" is the form field the validation will
validate, "criteria" is the validation criteria, and "message" is
the message that will be displayed when an error occurs.
OPTIONAL FUNCTION ATTRIBUTES:
FORM
----
{validate form="foo" ...}
If you are using a registered form other than the "default" form,
you must supply the form name with each corresponding validate tag.
TRANSFORM
---------
Note: This attribute has been deprecated, please set your transform functions with
the register_validator() function.
{validate field="foo" ... transform="trim"}
{validate field="foo" ... transform="trim,upper"}
"transform" is used to apply a transformation to a form value prior to
validation. For instance, you may want to trim off extra whitespace from
the form value before validating.
You can apply multiple transform functions to a single form value by
separating them with commas. You must register all transformation functions
with the register_transform() method. By default, 'trim' is registered.
Transformations will apply to every value of an array. If you want the
transformation applied to the array itself, you must specify with an "@"
symbol in front of each transform function:
{validate field="foo" ... transform="@notEmpty"}
If you want only a particular array element transformed, you must specify:
{validate field="foo[4]" ... transform="notEmpty"}
{validate field="foo[bar]" ... transform="notEmpty"}
TRIM
----
Note: the "trim" attribute has been deprecated, set your "trim" behavior
with a transform parameter of 'trim' in the register_validator() function.
Trim will trim whitespace from the form value before being validated, and
before the "empty" or "default" parameters are tested.
EMPTY
-----
Note: This attribute has been deprecated, please set your "empty" behavior with
the register_validator() function.
{validate id="foo" ... empty="yes"}
"empty" determines if the field is allowed to be empty or not. If
allowed, the validation will be skipped when the field is empty.
Note this is ignored with the "notEmpty" criteria.
HALT
----
Note: This attribute has been deprecated, please set your "halt" behavior with
the register_validator() function.
{validate id="foo" ... halt="yes"}
If the validator fails, "halt" determines if any remaining validators for
this form will be processed. If "halt" is yes, validation will stop at this
point.
ASSIGN
------
{validate id="foo" ... assign="error"}
"assign" is used to assign the error message to a template variable
instead of displaying the value. Use this when you don't want the
error message displayed right where the {validate ...} function is
called.
APPEND
------
{validate id="foo" ... append="error"}
"append" is used to append the error message to a template variable as an
array. This is an alternate to "assign". Use this when you want to loop over
multiple validation error messages and display them in one place. Example:
{foreach from=$error key="key" item="val"}
field: {$key} error: {$val}
{/foreach}
PAGE
----
{validate id="foo" page="1" ... message="fooError"}
When doing multi-page forms, each validator must have a page attribute to
identify the page that it belongs to. The SmartyValidator::set_page('1')
function must be called prior to displaying the given page.
TRANSFORM FUNCTIONS BUNDLED WITH SMARTYVALIDATE:
trim
----
example:
SmartyValidate::register_validator('fullname','FullName','notEmpty',false,false,'trim');
"trim": this trims whitespace from the beginning and end of the field. This
is useful to avoid confusing errors just because extra space was typed into
a field.
default
-------
example:
SmartyValidate::register_validator('value','Value','isInt',false,false,'default:0');
{validate id="value" message="..."}
"default": This sets the form value to the given default value in the case
it is empty. You can pass the default value as a parameter in the
register_validator() function (see above), or in the template as default="0".
makeDate
--------
example:
SmartyValidate::register_validator('start','StartDate','isDate',false,false,'makeDate');
SmartyValidate::register_validator('start','StartDate:year:month:day','isDate',false,false,'makeDate');
{validate id="start" message="..."}
"makeDate": this creates a date from three other form fields constructed by
using the "field" parameter as the prefix, such as StartDateYear,
StartDateMonth, StartDateDay in the first example. This is the common format
used with date fields generated by {html_select_date}. You can supply three
specific form fields separated by colons as in the second example above.
Here is a full example of how you might use "makeDate" transform function
and "isDateOnOrAfter" criteria function to compare two dates:
// in PHP script, setup validators
SmartyValidate::register_validator('setdate', 'EndDate', 'dummyValid', false, false, 'makeDate');
SmartyValidate::register_validator('compdate', 'StartDate:EndDate', 'isDateOnOrBefore');
// template
{* generate the EndDate value from EndDateYear, EndDateMonth, EndDateDay *}
{validate id="setdate"}
{* generate StartDate, then compare to EndDate *}
{validate is="compdate" message="start date must be on or after end date"}
{html_select_date prefix="StartDate"}
{html_select_date prefix="EndDate"}
{* we need these two hidden form fields to hold the values generated by makeDate *}
<input type="hidden" name="StartDate">
<input type="hidden" name="EndDate">
CRITERIA BUNDLED WITH SMARTYVALIDATE:
This is a list of the possible criteria you can use with
SmartyValidate. Some of them require their own special attributes.
Note: setting criteria in the template is deprecated, use the
register_validator() function instead.
notEmpty
--------
Tests if a field is empty (zero length). NOTE: using the "empty" flag with
this validator has no effect, it is ignored.
example:
PHP:
SmartyValidate::register_validator('v_fullname','FullName','notEmpty');
TEMPLATE:
{validate id="v_fullname" message="..."}
<input type="text" name="FullName">
isInt
-----
Tests if a field is an integer value.
example:
PHP:
SmartyValidate::register_validator('v_age','age','isInt');
TEMPLATE:
{validate id="v_age" message="..."}
<input type="text" name="age">
isFloat
-------
Tests if a field is a float value.
example:
PHP:
SmartyValidate::register_validator('v_fraction','fraction','isFloat');
TEMPLATE:
{validate id="v_fraction" message="..."}
<input type="text" name="fraction">
isNumber
--------
Tests if a field is either an int or float value.
example:
PHP:
SmartyValidate::register_validator('v_total','total','isNumber');
TEMPLATE:
{validate id="v_total" message="..."}
<input type="text" name="total">
isPrice
-------
Tests if a field has number with two decimal places.
example:
PHP:
SmartyValidate::register_validator('v_price','price','isPrice');
TEMPLATE:
{validate id="v_price" message="..."}
<input type="text" name="price">
isEmail
-------
Tests if field is valid Email address syntax.
example:
PHP:
SmartyValidate::register_validator('v_email','email','isEmail');
TEMPLATE:
{validate id="v_email" message="..."}
<input type="text" name="email">
isCCNum
-------
Tests if field is a checksummed credit card number.
example:
PHP:
SmartyValidate::register_validator('v_ccnum','ccnum','isCCNum');
TEMPLATE:
{validate id="v_ccnum" message="..."}
<input type="text" name="ccnum">
isCCExpDate
-----------
Tests if field is valid credit card expiration date.
example:
PHP:
SmartyValidate::register_validator('v_ccexp','ccexp','isCCExpDate');
TEMPLATE:
{validate id="v_ccexp" message="..."}
<input type="text" name="ccexp">
isDate
------
Tests if field is valid Date (parsible by strtotime()).
example:
PHP:
SmartyValidate::register_validator('v_startDate','startDate','isDate');
TEMPLATE:
{validate id="v_startDate" message="..."}
<input type="text" name="startDate">
isURL
------
Tests if field is valid URL (http://www.foo.com/)
example:
PHP:
SmartyValidate::register_validator('v_URL','URL','isURL');
TEMPLATE:
{validate id="v_URL" message="..."}
<input type="text" name="URL">
isEqual
-------
Tests if two fields are equal in value.
example:
PHP:
SmartyValidate::register_validator('v_pass','pass:pass2','isEqual');
TEMPLATE:
{validate id="v_pass" message="..."}
<input type="password" name="pass">
<input type="password" name="pass2">
isRange
-------
Tests if field is within a given range. Must give low and high params.
example:
PHP:
SmartyValidate::register_validator('v_mynum','num:1:5','isRange');
TEMPLATE:
{validate id="v_mynum" message="..."}
<input type="text" name="mynum">
isLength
--------
Tests if field is a given length. parameters 1 and 2 are min and max. use
-1 for no min or no max.
example:
PHP:
SmartyValidate::register_validator('v_username','username:3:10','isLength');
TEMPLATE:
{validate id="isLength" message="..."}
<input type="text" name="username">
isRegExp
--------
Tests a field against a regular expression. Expression must be fully
qualified preg_* expression. Note: it is recommended to use a custom plugin
instead of this validator, otherwise syntax limits may be a problem.
example:
PHP:
SmartyValidate::register_validator('v_username','username:!^\w+$!','isLength');
TEMPLATE:
{validate id="v_username" message="..."}
<input type="text" name="username">
isFileType
----------
Tests if an uploaded file is a given type (just checks the extention
name.) Note: This function is not backward compatible prior to version 2.4.
example:
PHP:
SmartyValidate::register_validator('v_myfile','myfile:jpg,gif,png','isFileType');
TEMPLATE:
{validate id="v_myfile" message="..."}
<input type="file" name="myfile">
isFileSize
----------
Tests if an uploaded file is under a given size. Size param can be suffixed
with "b" for bytes (default), "k" for kilobytes, "m" for megabytes and "g"
for gigabytes (kb, mb, and gb also work.) Note: This function is not
backward compatible prior to version 2.4.
example:
PHP:
SmartyValidate::register_validator('v_myimage','myimage:50k','isFileSize');
{validate id="v_myimage" message="..."}
<input type="file" name="myimage">
dummyValid
----------
This is a dummy criteria that always validates to true. This is useful to
apply a transformation to a field without actually applying a validation.
NOTE: Using the "empty" flag with this validator is ignored, dummyValid
always validates true anyways.
example:
PHP:
SmartyValidate::register_validator('v_initdate','StartDate','dummyValid',false,false,'makeDate');
TEMPLATE:
{validate id="v_initdate"}
<input type="text name="StartDate">
isDateEqual
-----------
Tests if a date is equal to another. The dates must be parsible by strtotime().
example:
PHP:
SmartyValidate::register_validator('date_equal', 'StartDate:EndDate', 'isDateEqual');
TEMPLATE:
{validate id="date_equal" message="..."}
<input type="text" name="StartDate">
<input type="text" name="EndDate">
isDateBefore
------------
isDateAfter
-----------
isDateOnOrBefore
----------------
isDateOnOrAfter
---------------
These all work similar to "isDateEqual" example above, but testing the dates
according to their respective function.
isCustom
--------
"isCustom" HAS BEEN REMOVED. Please see BUILDING YOUR OWN directly below.
VALIDATE INIT
-------------
Note: validate_init is deprecated now that we have register_validator(),
it shouldn't be necessary any more with no criteria in the templates.
example:
{validate_init form="foobar" halt="yes" assign="error_msg"}
{validate field="name" criteria="notEmpty" message="name cannot be empty"}
{validate field="pass" criteria="notEmpty" message="pass cannot be empty"}
{validate_init ... } sets parameter values that are implicitly passed to
each {validate ... } tag thereafter. This keeps the repeated verbosity of
{validate ... } tags to a minimum. Any initialized parameter can be
overridden in each {validate ... } tag. You can re-initialize the
parameters by calling {validate_init ... } again.
BUILDING YOUR OWN CRITERIA/TRANSFORM FUNCTIONS:
Building your own custom functions has never been easier. First, we'll make
up a couple of new functions in the template. We'll make one criteria
function and one transform function.
"isValidPassword" and "upper" are names we are using in the validator
registration reference your new custom functions. These are not necessarily
real PHP function names, it just the names used by the validator.
You can do one of two things: make Smarty plugins so the new functions are
automatically found and used, or write PHP functions and register them
directly.
SMARTY_PLUGIN METHOD:
In your Smarty plugin directory, create a new file named
validate_TYPE.NAME.php where TYPE is either 'criteria' or 'transform', and
NAME is the name of the new function. The corresponding function names in
the plugin files must follow the convention smarty_validate_TYPE_NAME()
where TYPE and NAME are the same TYPE and NAME from the filename. The NAME
is the criteria/transform name that will be used in the template. In our
example, the filenames will be validate_criteria.isValidPassword.php, and
validate_transform.upper.php. (The template will be calling
criteria="isValidPassword" and transform="upper")
validate_criteria_isValidPassword.php
-------------------------------------
<?php
function smarty_validate_criteria_isValidPassword($value, $empty, &$params, &$formvars) {
if(strlen($value) == 0)
return $empty;
// we might have a function we call to test the password
// against a database
return is_valid_password($formvars['username'], $value);
}
?>
validate_transform_upper.php
----------------------------
<?php
function smarty_validate_transform_upper($value, &$params, &$formvars) {
return strtoupper($value);
}
?>
Your criteria functions must contain the four parameters given in the
example above. The first parameter is the form field value being validated.
The second is the boolean "empty" value given as a parameter to the
validator (or false if none was given). $params contains all the parameters
passed to the validator, and $formavars contains all the form information.
The last two are passed by reference so you can edit the original values if
need be.
All custom criteria should return a boolean "true" or "false" value to
indicate to SmartyValidate that the validation passed or failed. You do NOT
print error messages inside the function, except for errors dealing with a
misconfiguration of the validator such as a missing parameter. If the
validator fails, the error message for the person filling out the form
should already be set in the template {validator ... message="error!"}
Transform functions have three parameters, the first being the field value
being transformed, and the second is all the parameters passed to the
validator, and the third is the form variables. The last two are passed by
reference so you can edit the original values if need be. The transform
function should return the transformed value of $value.
If the file names and function names follow the above convention, no
registration of the functions are necessary, SmartyValidate will locate and
use the plugins. All of the functions that ship with SmartyValidate are plugins.
MANUAL REGISTER METHOD:
You can manually register your functions instead of using plugins. This is
useful if you have a function specific to one application and a Smarty
plugin may not be the most practical place for it. You can also register
class methods this way.
First example will be a straight forward PHP function:
function check_pass($value, $empty, &$params, &$formvars) {
// do your logic here, check password, return true or false
}
After your function exists, you can register it with SmartyValidate:
SmartyValidate::register_criteria('isValidPassword','check_pass');
Transformation functions are done the same way:
SmartyValidate::register_transform('upper','my_upper_func');
You can also register class methods. First, you must register the object
with SmartyValidate, then register the method(s):
SmartyValidate::register_object('my_obj', $my_obj);
SmartyValidate::register_criteria('isValidPassword','myobj->check_pass');
SmartyValidate::register_transform('upper','myobj->my_upper_method');
Calling PHP functions or class methods look exactly the same, you just use
the registered name(s) like so:
SmartyValidate::register_validator('v_foo','foo','isValidPassword',false,false,'upper');
Just like functions that come with SmartyValidator, all functions are
applied to every element of an array coming from the form. If you want your
function to act on the array itself, you must specify that in the
registration:
SmartyValidate::register_validator('v_foo','foo','@isValidPassword',false,false,'@upper');
If you want a specific array element validated, you must specify:
SmartyValidate::register_validator('v_foo','foo[4]','isValidPassword',false,false,'upper');
SmartyValidate::register_validator('v_foo','foo[bar]','isValidPassword',false,false,'upper');
CREDITS:
Thanks to the many people who have submitted bug reports, suggestions, etc.
Edwin Protomo
John Blyberg
Alexey Kuimov
boots (from forums)
xces (from forums)
electr0n (from forums)
Justin (from forums)
hristov (from forums)
kills (from forums)
Anyone I missed, let me know!
COPYRIGHT:
Copyright(c) 2004-2005 New Digital Group, Inc. All rights reserved.
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 2.1 of the License, or (at
your option) 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.
|