[web] Zend framework form element, filter, validator整理

Form Element
Zend_Form_Element_Button
button

Zend_Form_Element_Captcha

<?php
// Using single captcha key:
$element = new Zend_Form_Element_Captcha('foo', array(
    'label' => "Please verify you're a human",
    'captcha' => array(
        'captcha' => 'Figlet',
        'wordLen' => 6,
        'timeout' => 300,
    ),
));
?>
Zend_Form_Element_Checkbox
checkbox (or many checkboxes at once with multiCheckbox)

Zend_Form_Element_File

<?php
$element = new Zend_Form_Element_File('foo');
$element->setLabel('Upload an image:')
        ->setDestination('/var/www/upload');
// ensure only 1 file
$element->addValidator('Count', false, 1);
// limit to 100K
$element->addValidator('Size', false, 102400);
// only JPEG, PNG, and GIFs
$element->addValidator('Extension', false, 'jpg,png,gif');
$form->addElement($element, 'foo');

$form->setAttrib('enctype', 'multipart/form-data');
//in controller
if (!$form->isValid()) {
    print "Uh oh... validation error";
}
 
if (!$form->foo->receive()) {
    print "Error receiving the file";
}
 
$location = $form->foo->getFileName();
?>
Zend_Form_Element_Hidden
hidden
Zend_Form_Element_Hash

Zend_Form_Element_Image
image

Zend_Form_Element_MultiCheckbox
Zend_Form_Element_Multiselect
Zend_Form_Element_Password
password

Zend_Form_Element_Radio
radio

Zend_Form_Element_Reset
reset

Zend_Form_Select
select (both regular and multi-select types)

Zend_Form_Submit
submit
Zend_Form_Element_Text
text

Zend_Form_Element_Textarea
textarea

Filter
Zend_Filter_Alnum

Zend_Filter_Alpha
數字會被過濾掉
'hello 123' => 'hello'

Zend_Filter_BaseName
'/home/q110185/filename' =>'filename'

Zend_Filter_Boolean
<?php
// converts 0 and '0' to false
$filter = new Zend_Filter_Boolean(array(
    'type' => array(
        'integer',
        'zero',
    ),
));
?>

boolean: Returns a boolean value as is.
integer: Converts an integer 0 value to FALSE.
float: Converts a float 0.0 value to FALSE.
string: Converts an empty string '' to FALSE.
zero: Converts a string containing the single character zero ('0') to FALSE.
empty_array: Converts an empty array to FALSE.
null: Converts a NULL value to FALSE.
php: Converts values according to PHP when casting them to BOOLEAN.
false_string: Converts a string containing the word "false" to a boolean FALSE.
yes: Converts a localized string which contains the word "no" to FALSE.
all: Converts all above types to BOOLEAN.

Zend_Filter_Callback

Zend_Filter_Compress and Zend_Filter_Decompress
壓縮解壓縮
參數 有Bz2、Gz、Lzf、Rar、Tar、Zip

Zend_Filter_Digitls
'hello 123' => '123'

Zend_Filter_Dir
'/etc/passwd' => '/etc'

Zend_Filter_Encrypt and Zend_Filter_Decrypt 
加解密用

Zend_Filter_HtmlEntities

Zend_Filter_Int
'-4 ddfdf 334' => '-4'

Zend_Filter_LocalizedToNormalized and Zend_Filter_NormalizedToLocalized
The following input types can be normalized and localized:
integer: Integer numbers. Normalization returns the english notation
float: Float numbers. Normalization returns the english notation
numbers: Other numbers, like real. Normalization returns the english notation
time: Time values. The normalized value is a named array
date: Date values. The normalized value is a named array
<?php
// Initiate the filter
$filter = new Zend_Filter_LocalizedToNormalized();
$filter->filter('123.456,78');
// returns the value '123456.78'

// Numeric Filter
$filter = new Zend_Filter_LocalizedToNormalized(array('precision' => 2));
 
$filter->filter('123.456');
// returns the value '123456.00'
 
$filter->filter('123.456,78901');
// returns the value '123456.79'

// Initiate the filter
$filter = new Zend_Filter_LocalizedToNormalized();
$filter->filter('12.April.2009');
// returns array('day' => '12', 'month' => '04', 'year' => '2009')
?>

Zend_Filter_PregReplace
<?php
$filter = new Zend_Filter_PregReplace(array('match' => 'bob',
                                            'replace' => 'john'));
$input  = 'Hy bob!";
 
$filter->filter($input);
// returns 'Hy john!'
?>

Zend_Filter_RealPath
<?php
$filter = new Zend_Filter_RealPath();
$path   = '/www/var/path/../../mypath';
$filtered = $filter->filter($path);
 
// returns '/www/mypath'
?>

Zend_Filter_StringToLower
<?php
$filter = new Zend_Filter_StringToLower();
 
print $filter->filter('SAMPLE');
// returns "sample"

//[optional] set encode
// using UTF-8
$filter = new Zend_Filter_StringToLower('UTF-8');
?>

Zend_Filter_StringToUpper


Zend_Filter_String_Trim
去除前後的空白

Zend_Filter_StripNewLines
去除'\n\r'

Zend_Filter_StripTags 
去除Tag (官方不建議用這個來防禦XSS)

<?php
$filter = new Zend_Filter_StripTags(array('allowTags' => 'a'));
 
$input  = "A text with <br/> a <a href='link.com'>link</a>";
print $filter->filter($input);
// returns: A text with a <a href='link.com'>link</a>
?>




Validator
Zend_Validate_Alnum

Zend_Validate_Alpha

Zend_Validate_Barcode

Zend_Validate_Between

<?php
$valid  = new Zend_Validate_Between(
    array(
        'min' => 0,
        'max' => 10,
        'inclusive' => false
    )
);
$value  = 10;
$result = $valid->isValid($value);
// returns false
?>


Zend_Validate_Callback

Zend_Validate_CreditCart
Allow creditCart:

nstituteConstant
American ExpressAMERICAN_EXPRESS
China UnionPayUNIONPAY
Diners Club Card BlancheDINERS_CLUB
Diners Club InternationalDINERS_CLUB
Diners Club US & CanadaDINERS_CLUB_US
Discover CardDISCOVER
JCBJCB
LaserLASER
MaestroMAESTRO
MasterCardMASTERCARD
SoloSOLO
VisaVISA
Visa ElectronVISA


<?php
$valid = new Zend_Validate_CreditCard(array(
    Zend_Validate_CreditCard::AMERICAN_EXPRESS,
    Zend_Validate_CreditCard::VISA
));
?>


Zend_Validate_Date
default date format for Zend_Validate_Date is 'yyyy-MM-dd'.

<?php
$validator = new Zend_Validate_Date(array('format' => 'yyyy MMMM', 'locale' => 'de'));
 
$validator->isValid('2010 Dezember'); // returns true
$validator->isValid('2010 June');     // returns false
?>


Zend_Validate_Db_RecordExists and Zend_Validate_Db_NoRecordExists
驗證資料庫有無存在這資料
[Params]
adapter: The database adapter which will be used for the search.
exclude: Sets records which will be excluded from the search.
field: The database field within this table which will be searched for the record.
schema: Sets the schema which will be used for the search.
table: The table which will be searched for the record.


<?php
//Check no other users have the username
$user_id   = $user->getId();
$validator = new Zend_Validate_Db_NoRecordExists(
    array(
        'table' => 'users',
        'field' => 'username',
        'exclude' => array(
            'field' => 'id',
            'value' => $user_id
        )
    )
);
 
if ($validator->isValid($username)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}
?>


Zend_Validate_Digits

Zend_Validate_EmailAddress

Zend_Validate_Float


Zend_Validate_GreaterThan

<?php
$valid  = new Zend_Validate_GreaterThan(array('min' => 10));
$value  = 10;
$return = $valid->isValid($value);
// returns true
?>



Zend_Validate_Hex


Zend_Validate_Hostname

Zend_Validate_Identical

<?php
$form->addElement('password', 'elementOne');
$form->addElement('password', 'elementTwo', array(
    'validators' => array(
        array('identical', false, array('token' => 'elementOne'))
    )
));
?>


Zend_Validate_InArray

<?php
$validator = new Zend_Validate_InArray(array('key' => 'value',
                                             'otherkey' => 'othervalue'));
if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}
?>


Zend_Validate_Int


Zend_Validate_Ip
default ipv4 and ipv6都可()

  • llowipv4: Defines if the validator allows IPv4 adresses. This option defaults to TRUE.
  • allowipv6: Defines if the validator allows IPv6 adresses. This option defaults to TRUE.

Zend_Validate_Isbn

Zend_Validate_LessThan

<?php
$valid  = new Zend_Validate_LessThan(array('max' => 10));
$value  = 10;
$return = $valid->isValid($value);
// returns true
?>


Zend_Validate_NotEmpty


Zend_Validate_PostCode
郵遞區號

Zend_Validate_Regex

<?php
$validator = new Zend_Validate_Regex(array('pattern' => '/^Test/');
 
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns true
$validator->isValid("Pest"); // returns false
?>


Zend_Validate_StringLength

  • encoding: Sets the ICONV encoding which has to be used for this string.
  • min: Sets the minimum allowed length for a string.
  • max: Sets the maximum allowed length for a string.



留言

這個網誌中的熱門文章

電腦網路project