本文實例講述了Zend Framework校驗器Zend_Validate用法。分享給大家供大家參考,具體如下:
引言:
是對輸入內容進行檢查,并生成一個布爾結果來表明內容是否被成功校驗的機制。
如果isValid()方法返回False,子類的getMessage()方法將返回一個消息數組來解釋校驗失敗的原因。
為了正確地返回消息與錯誤內容,對于isValid()方法的每次調用,都需要清除前一個isValid()方法調用所導致的消息和錯誤。
案例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?php require_once 'Zend/Validate/EmailAddress.php' ; function c_email( $email ) { $validator = new Zend_Validate_EmailAddress(); if ( $validator ->isValid( $email )){ echo "輸入的E-mail地址:" ; echo $email . "有效!<p>" ; } else { echo "輸入的E-mail地址:" ; echo $email . "無效!" ; echo "失敗消息為:<p>" ; foreach ( $validator ->getMessages() as $message ){ echo $message . "<p>" ; } foreach ( $validator ->getErrors() as $error ){ echo $error . "<p>" ; } } } $e_m2 = "abc#123.com" ; c_email( $e_m1 ); c_email( $e_m2 ); |
結果:
輸入的E-mail地址:[email protected]有效!
輸入的E-mail地址:abc#123.com無效!失敗消息為:
'abc#123.com' is not a valid email address in the basic format local-part@hostname
emailAddressInvalidFormat
說明:
在引入類之后,定義一個驗證函數,在函數中實例化類。用isValid()方法來進行驗證,不同的子類驗證器驗證的內容是不一樣的。
同時通過getMessages()方法和getErrors()方法來。
源碼賞析:
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
|
public function isValid( $value ) { if (! is_string ( $value )) { $this ->_error(self::INVALID); return false; } $matches = array (); $length = true; $this ->_setValue( $value ); // Split email address up and disallow '..' if (( strpos ( $value , '..' ) !== false) or (!preg_match( '/^(.+)@([^@]+)$/' , $value , $matches ))) { $this ->_error(self::INVALID_FORMAT); return false; } $this ->_localPart = $matches [1]; $this ->_hostname = $matches [2]; if (( strlen ( $this ->_localPart) > 64) || ( strlen ( $this ->_hostname) > 255)) { $length = false; $this ->_error(self::LENGTH_EXCEEDED); } // Match hostname part if ( $this ->_options[ 'domain' ]) { $hostname = $this ->_validateHostnamePart(); } $local = $this ->_validateLocalPart(); // If both parts valid, return true if ( $local && $length ) { if (( $this ->_options[ 'domain' ] && $hostname ) || ! $this ->_options[ 'domain' ]) { return true; } } return false; } |
解析:
這是主要的驗證函數內容,分成了多種情況進行驗證,有是否字符串,有是否符合郵箱規則,有長度是否符合,最終都符合才返回true。
希望本文所述對大家基于Zend Framework框架的PHP程序設計有所幫助。