【发布时间】:2012-01-30 14:52:51
【问题描述】:
我需要一个 php 验证器类来验证用户输入。
我希望它能够接受一个 assoc 字段数组 => 值,例如:
array(
"username" => "Alex",
"email_address" => "@@#3423£alex@my.mail.com"
);
然后返回一个这样的错误数组:
array(
"username" => "",
"email_address" => "Invalid Email Address"
);
但我真的很想知道我到底要怎么做!
我已经阅读了无数关于 PHP 验证器的页面,并了解到最好的方法是使用策略模式。但我不知道怎么做??
就像...这是我到目前为止所得到的:
class Validator {
private
$_errors,
$_fields,
static private $_map = array (
"firstname" => "name",
"surname" => "name",
"agency_name" => "name",
"agency_office" => "name",
"username" => "username",
"email_address" => "email_address",
);
public function __construct( array $fields ) {
$this->_fields = $fields;
}
public function validate() {
foreach ( $this->_fields as $field => $value ) {
if ( method_exists( __CLASS__, self::$_map[$field] ) ) {
if ( in_array( $field, self::$_map ) ) {
$this->{self::$_map[$field]}( $field, $value );
}
}
else {
die( " Unable to validate field $field" );
}
}
}
public function get_errors() {
return $this->_errors;
}
private function name( $field, $value ) {
if ( !preg_match( "/^[a-zA-Z]{2,50}$/", $value ) ) {
$this->errors[$field] = "Invalid. Must be 2 to 50 alphanumerical characters";
}
}
private function username( $field, $value ) {
if ( !preg_match( "/^[a-zA-Z0-9_\-]{10,50}$/", $value ) ) {
$this->errors[$field] = "Invalid. Must be 10 to 50 characters. Can contain digits, characters, _ (underscore) and - (hyphen)";
}
}
private function password( $field, $value ) {
if ( !preg_match( "/^[a-zA-Z0-9\.\-]{8,30}$/", $value ) ) {
$this->_errors[$field] = "Invalid. Must be 8 to 30 characters. Can contain digits, characters, . (full stop) and - (hyphen)";
}
}
private function email_address( $field, $value ) {
if ( !filter_var( $value, FILTER_VALIDATE_EMAIL ) ) {
$this->_errors[$field] = "Invalid Email Address";
}
}
}
问题在于,它甚至不考虑已注册用户名的数据库连接,
也是密码不匹配
我现在刚刚遇到了程序员的障碍,它在内部摧毁了我:(
任何人都可以解释所需的类和每个类需要做的功能吗?
我确实需要输入和输出采用已经解释过的格式!
非常感谢互联网人!
【问题讨论】:
-
你看过现有的图书馆是如何做到的吗? Symfony Components 和 Zend Framework 都有很好的解决方案。它们比您这里的要大,但也涵盖更多案例。
-
完全同意 Louis-Philippe 的观点,Zend Framework 具有完整的验证框架和易于理解的可扩展框架。我敦促您考虑使用此类框架,而不是自己制作。
-
我认为这是一种自我教育。以防万一了解它如何工作,而不仅仅是使用它。
标签: php oop validation design-patterns strategy-pattern