我正在尝试验证寄存器表单,但我似乎无法建立连接以允许AJAX验证表单。到目前为止,验证错误位于Validate.php
文件中,signup.php
文件中是验证规则。
以下是我的代码: Validate.php
<?php
class Validate {
private $_passed = false,
$_errors = array(),
$_db = null;
public function __construct() {
$this->_db = DB::getInstance();
}
public function check($source, $items = array('name')) {
foreach($items as $item => $rules) {
foreach($rules as $rule => $rule_value) {
$value = trim($source[$item]);
$item = escape($item);
if($rule === 'required' && empty($value)) {
$this->addError("{$item} is required");
}
else if (!empty($value)) {
switch($rule) {
case 'min':
if (strlen($value) < $rule_value) {
$this->addError("{$item} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if (strlen($value) > $rule_value) {
$this->addError("{$item} has a maximum of {$rule_value} character limit.");
}
break;
case 'unique':
$check = $this->_db->get($rule_value, array($item, '=', $value));
if($check->count()) {
$this->addError("{$item} already exists.");
};
break;
case 'matches':
if ($value != $source[$rule_value]) {
$this->addError("Your entry does not match {$item}.");
}
break;
}
}
}
}
if(empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError($error) {
$this->_errors[] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
signup.php
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'First Name' => array(
'required' => true,
'max' => 40
),
'last_name' => array(
'name' => 'Last Name',
'required' => true,
'max' => 40
),
'email' => array(
'name' => 'Email',
'required' => true,
'max' => 50,
'unique' => 'users'
),
'password' => array(
'name' => 'Password',
'required' => true,
'min' => 6,
'max' => 30
),
'c_psw' => array(
'required' => true,
'matches' => 'password'
)
));
if ($validation->passed()) {
//register user
Session::flash('success', 'You have registered successfully. Please check your email inbox for the activation email. Please also check your Junk email folder just in case the activation email was sent there instead of your inbox.');
}
else {
//output errors
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
如果有帮助:这是Input.php文件:
class Input {
//exists
public static function exists ($type = 'post') {
switch($type) {
case 'post':
return(!empty($_POST)) ? true :false;
break;
case 'get':
return(!empty($_GET)) ? true :false;
break;
default:
return false;
break;
}
}
//get
public static function get($item) {
if(isset($_POST[$item])) {
return $_POST[$item];
}
else if(isset($_GET[$item])) {
return $_GET[$item];
}
return '';
}
}