Formcat class for PHP
V1.02 Feb 2005 (c) 2005 Joey Wong (joey@163.com)[MSN:gzjoey@hotmail.com]
This software is dual licensed using BSD-Style
and LGPL. This means you can use it in compiled proprietary and commercial products.
Useful Link: Formcat
Offical site Formcat
SourceForge Project Formcat
on Hotscripts
Smarty Template Environment
SmartyValidate
Introduction
I.Getting Started.
1.What is Formcat
2.Requirments
3.Installation
4.A simple example
II.Formcat in the template
5.Synopsis & Extra Attributes
6.Validators
6.1 notEmpty
6.2 isRange
6.3 isLength
6.4 cboxChecked
6.5 radioChecked
6.6 isSelected
6.7 isEmail
6.8 isInt
6.9 isFloat
6.10 isDate
6.11 isURL
6.12 isEqual
6.13 isFileSize
6.14 isFileType
6.15 dateCompare
6.16 isRestrict
6.17 isRegExp
III.Formcat in PHP
7.Synopsis
8.Add customizing script into a form validating function.
IV. Customizing validator
9.Synopsis
10.Expand the Formcat
V. Credits
VI. Copyrights
Formcat is a class for performing form validation
on the client side.Its goal is to generate Javascript code to validate forms
before they are submited to the server.
It works as a plug-in for the Smarty template engine. It is a good complement
SmartyValidate plug-in that performs server side validation.It supports many
built-in validation criteria: empty, range, length,checkbox, radio button, integer,
float, email, credit card, list menu,date, date comparison, equality between
fields, file size, file type, custom validator calls.
{formcat ...} tags can be located anywhere in the templates, regardless of where the corresponding fields are located in the form
I.Getting Started.
1. What is Formcat
"Formcat",it's smarty cat,a plug-in for form validation in client-side.You
don't need to program the scripts to validate the input data from the form after
using the "Formcat".
"Say good-bye to the tedious and time-consuming task, Formcat go!".
You must enable session management prior to using Formcat . Do this by calling session_start() at the top of your PHP application.
Formcat also requires the Smarty template environment.
3. Installation:
To install Formcat:
* Copy the 'formcat.class.php' file and "validators" directory(lite version don't need to do that)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.)
4. A simple example:
Here is a full working example of how to use Formcat,Now let's see what
the Formcat performs:
index.tpl (0riginal)
========================
<form name="formReg" action="register.php" method="POST">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pwd"><br>
Confirm Password : <input type="password" name="pwd2"><br>
Email: <input type="text" name="email"><br>
<center><input type="submit"></center>
</form>
index.tpl (processed by Formcat)
===================================
{catform form="formReg"}
<form name="formReg" action="register.php" method="POST">
Username : <input type="text" name="username">
{formcat check="notEmpty" field="username" message="You
MUST input username."}
<br>
Password : <input type="password" name="pwd">
{formcat check="notEmpty" field="pwd" message="You
MUST input password."}
<br>
Confirm Password : <input type="password" name="pwd2">
{formcat check="notEmpty" field="pwd2" message="You
MUST input confirm password."}
{formcat check="isEqual" field="pwd" field2="pwd2"
message="The password Must be same as the confirm password"}
<br>
Email: <input type="text" name="email">
{formcat check="isEmail" field="email" message="You
should input a valid email address"}
<br>
<center><input type="submit"></center>
</form>
{/catform}
index.php
=======================================
<?php
session_start();
// you will need to setup Smarty if
// the defaults are not correct.
require('Smarty.class.php');
require('formcat/formcat.class.php');
$smarty =& new Smarty;
$fc = new formcat;
$smarty->register_outputfilter(array(&$fc,'fcOutputFilter'));
$smarty->display('form.tpl');
You can view the source of outputed HTML,the validating javascript has been generated.
II.Formcat in the template
5. Synopsis:
All formcat operations in the template are realized using the {catform}{/catform} and {formcat} tags.
{catform}{/catform} is a container tags.In order to identify the multi-forms.though there 's only one form,you still use them.
{catform form="formname"}.....{/catform}
Correspondence {formcat ...} validator tags must contain in
{catform}...{/catform} tags
Catform Extra Attributes:
Catform extra function tags could be use after formcat 1.01 version. Here's
extra attributes for {catform} tags
for example : {catform form="login" flashFocus="TRUE"
submitOnce="TRUE"}
please attention
:
1. extra functions which generated by extra attributes of formcat are tested
on some leading browsers: IE , FireFox , Opera. However, they can't assured
that they can run on other browsers normally.
2. catform extra attributes are case-sensitive. you should according following
formats to use them
- flashFocus
If flashFocus is set TRUE, corresponding input object will
blink withtwo colors for hint when an error occurs.This attribute just work
with validators
which has focus attribute.otherwise will show nothing.
flashFocus makes input object which on focus blink with two colors. Two flash
color can changed by yourself. Just edit them $flashColor,$flashColor2
in "formcat.class.php". Another parameter which I
should mention.that's $keepFlashColor. $keepFlashColor set
"1",input object's background color will be changed to $flashColor
after blink. otherwise ,input object's background color will be keep original
color.
You can find those parameters in "formcat.class.php"
header area.
It's a good idea which contributed by Mr. Sylvestre Ledru to
guide users to input. Thanks for Mr. Sylvestre Ledru from France.
eg: {catform form="form_name" flashFocus="TRUE"}
- submitOnce
If submitOnceis set TRUE, corresponding form submit
button will be disable after you pressed submit once. this
function used to prevent click submit repeatedly.
submitOnce alert message can changed by yourself. Just edit "$defaultSubmitOnceMsg"
in "formcat.class.php".
eg: {catform form="form_name" submitOnce="TRUE"}
6. Validators:
Validators tags are completely by {formcat ...} as opening. There're required attributes to a {formcat ...}.But each validator tags has different attributes.Majority,All validator tags attributes almost have "check","field","message" and "focus". except "isDate" and "dateCompare".they has other attributes but still has "check" attribute.
"field" - is the form field the validation will
validate.
"check" - is the validation criteria.
"message" - the message that will be displayed when an error
occurs.
"focus" - optional attribute.default is TRUE.focus
the input element when an error occurs.
(using javascript's .focus())
Now let's take a tour for Formcat validators:
6.1 notEmpty
"notEmpty": field is not empty.
eg: {formcat check="notEmpty" field="fieldname"
message="..."[ focus="false"]}
6.2 isRange
"isRange":checks if field is within a given range. "min"
and "max" attributes required.
eg: {formcat check="isRange" field="fieldname" min="3" max="8" message="..." [ focus="false"]}
6.3 isLength
"isLength":checks if field is a given length. "min" and
"max" attributes required.
eg: {formcat check="isLength" field="fieldname"
min="5" max="12" message="..."[ focus="false"]}
6.4 cboxChecked
"cboxChecked": check if a checkbox has been checked.
eg: {formcat check="cboxChecked" field="fieldname"
message="..."}
for attention: cboxChecked allow
that "fieldname" is appear as array mode. eg: There are many checkbox
elements,named as "job[]", the Formcat validator tags will be :{formcat
check="cboxChecked" field="jobs[]" message="must choose
a job title!"}.
6.5 radioChecked
"radioChecked": check if a radio button has been checked.
eg: {formcat check="radioChecked" field="fieldname"
message="..."}
6.6 isSelected
"isSelected": checks if an option has been selected
eg: {formcat check="isSelected" field="fieldname"
index="1" message="..."}
Unique attribute:
index - "the starting index of list menu",the selected
index must high than that.
6.7 isEmail
"isEmail": check if field is valid Email address
eg: {formcat check="isEmail" field="fieldname" message="..."
[ focus="false"]}
6.8 isInt
"inInt" : check if field is an integer value.
eg: {formcat check="isInt" field="fieldname" message="..."
[ focus="false"]}
6.9 isFloat
"isFloat": check if field is an float value.
eg: {formcat check="isFloat" field="fieldname" message="..."
[ focus="false"]}
6.10 isDate
"isDate": check if field is valid Date.
eg: {formcat check="isDate" year="year field" month="month
field" day="day field"}
6.11 isURL
"isURL": check if field is valid URL.
eg: {formcat check="isURL" field="fieldname" message="..."
[ focus="false"]}
6.12 isEqual
"isEqual":checks if two fields are equal in value. "field2"
attribute required.
eg: {formcat check="isEqual" field="fieldname1"
field2="fieldname2" message="..."[ focus="false"]}
Unique attributes:
field2 - "field2" value must be the same as "field"
value.if "focus" is true(default is true),it will
be focus on field2
6.13 isFileSize
"isFileSize": checks if an uploaded file is under a given size.(unit:KBytes).
eg: {formcat check="isFileSize" field="file fieldname" min="10" max="1024" message="..."[ focus="false"]}
Warning: "isFileSize"
validator is working with ActiveX object, the "security warning dialog
box" will appeared possibly.
Strong recommend that you validate the file size by SmartyValidate or other
server-side validations.
6.14 isFileType
"isFileType":checks if an uploaded file is a given type (just checks
the extention name.) Since this is
validating an uploaded file.
eg: {formcat check="isFileType" field="file fieldname"
type="jpg,gif,bmp" message="..."[ focus="false"]}
Unique attributes:
type - allow upload file extensions,separate each by comma.
6.15 dateCompare
"dateCompare": use "after_year"-"after_month"-"after_day"
minus "before_year"-"before_month"-"before_day"
if the result < 0 ,return false and show the error message.
if "dateEqual" attribute set TRUE.then the [after_date] must
be the same as the [before_date].
if "compToday" attribute set TRUE then the [before_date] replaced
with TODAY and compare with the [after_date]
eg: {formcat check="dateCompare" after_year="yrfield1"
after_month="mfield1" after_day="dfield1" before_year="yrfield2"
before_month="mfield2" before_day="dfield2" [dateEqual="TRUE"]
[compToday="TRUE"]}
6.16 isRestrict
"isRestrict": check if field has restrict letter.
eg: {formcat check="isRestrict" field="fieldname"
restrict="restrict letters" message="..."[ focus="false"]}
Unique Attributes:
restrict - restrict letters,for example : you are not allow
the user input email , u can set restrict="@" .
and if you are not allow the data include whitespace , u can set restrict="
"
for attention: there are two special
keywords can be the restrict attribute
"notab" - escape all the tab ("\t\n\r")
"specialchars" - escape all the special char (><,[]{}?/+=|\\\'\\\":;~!@#*$%^&()`)
6.17 isRegExp
"isRegExp": checks a field against a regular expression. "expression"
attribute required
eg: {formcat check="isRegExp" field="fieldname"
expression="regex" message="..."[ reverse="TRUE"
focus="false"]}
Unique Attribute:
expression - regular expression
reverse - reverse judge.default is FALSE. the inputed data
must escape the "expression". if set TRUE, the data must match the
"expression"
Warning: "expression"
as regular expression pattern.Formcat is using Javascript 's RegExp object to
match the data.To prevent escape by PHP,you should pay attention the expression
formcat.for example:
It's a formcat isRegExp validator . to check the inputed data whether match
the regular expression(this example is integer).
{formcat check="isRegExp" field="item" expression="\\\b\\\d+\\\b"
reverse="TRUE" message="item must be integer"}
III. Formcat in PHP
7. Synopsis:
Most Formcat operations in the PHP Code depend on the "formcat
class", defined in "formcat.class.php".
In a general way,we start the formcat as following:
<?php
session_start(); //don't forget
require('Smarty.class.php');
require('formcat/formcat.class.php');
....
$smarty =& new Smarty;
$fc = new formcat; //create an instance of formcat
//register the formcat::fcOutputFilter as an output filter of Smarty
$smarty->register_outputfilter(array(&$fc,'fcOutputFilter'));
....
$smarty->display('form.tpl');
?>
Let's review the Formcat starting main steps:
1.You should enable session by calling "session_start();"
at the top of your PHP program.
2.You should include the "Smarty class" and "Formcat class"
files.
3.Creates instances of Smarty and Formcat.
4.Register "Formcat::fcOutputFilter" as an output filter of Smarty
If you are the senior developer,you can package them.or creates a new class
to combine them.
8. Add customizing script into a form validating function.
Formcat has many validator criteria which use frequently.However,in some cases,you
may want to include some unique scripts into the main validating function.
So far,Formcat has a way to solve it. that's "addCustomJs()"
method.
Method:
function addCustomJs($formName,$jsStr)
============================================
eg:
$customJs = "if(fc['username'].value=='joey'){\n".
"alert('....');\n return false;\n}\n";
formcat::addCustomJs('frmLogin',$customJs);
------------------------------------------------------------------
Add your customizing javascript to the validating function of "$formName".For
Attention,you only can add Javascript.
Formcat 1.01 has two version,one is "PRO version" ,another is "Lite
version".their unique difference is "Lite version" combine all
functions of validators into "formcat.class.php" but "PRO version".
10. Expand the formcat:
Building your own custom functions has been easier.Let's see how to.
Formcat's validator functions
===============================
void js_validator_criteriaName(obj &$formcat,array $params)
All attributes passed to template functions from the template are contained
in the $params as an
associative array. Either access those values directly, e.g. $params['max']
or use extract($params)
to import them into the symbol table.
$formcat is a reference of formcat object.
The output (return value) of the function will be generated Javascript
Example:
function js_validator_noWhiteSpace(&$formcat,$params){
extract($params);
$message = (empty($message))?sprintf($formcat->defaultErrMsg,$field):$message;
$formcat->addFocus($field,$focus);
if($field!=''){
$str = "\n //check whitespace\n".
"var badChar = \"" "\"\n".
"var i;\n".
"for (i = 0; i < fc['".$field."'].value.length; i++){\n".
"var c = fc['".$field."'].value.charAt(i);\n".
"if (badChar.indexOf(c)>=0) {\n".
"alert('$message');\n".
$focusStr."return false;\n".
"}\n}\n";
return $str;
}
}
If you are using "Formcat lite version" just put these code into "formcat.class.php".Otherwise,you
should create a file which named "js_validator_criteriaName.php"
to fill by these code,and copy thefile to the directory "validators"
The "Formcat" tags will be :
{formcat check="criteriaName" attributeName="..."
.......}
V.Credits
Author : Joey Wong
Special thanks:
Charlotte Chan
Messju Mohr (from Smarty forum)
Monte Ohrt (from Smarty forum)
boots (from Smarty forum)
Ganesh (from India)
Sylvestre Ledru(from France)
VI. Copyrights
Copyright(c) 2005 JUSTTO.COM and Joey Wong. 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.