我一直在尝试制作一个自定义验证类,但令我困扰的是它只是测试它看到的最后一个元素。我需要它来测试我放入其中的所有内容。
<?php
class Valid {
function validate(array $args){
$errors = NULL;
//********************************
//Find each key validation.
//********************************
foreach ($args as $key => $value){
//*********************************
//Check for letters only, a-z, A-Z.
//*********************************
if ($key == 'letters'){
$letters = preg_match('/^\pL+$/u', $value) ? TRUE : FALSE;
$letters_value = $value;
$letters_array[] = $letters;
}
//*********************************
//Check for numbers only, 0-9.
//*********************************
if ($key == 'numbers'){
$numbers = preg_match('/^[0-9]+$/', $value) ? TRUE : FALSE;
$numbers_value = $value;
$numbers_array[] = $numbers;
}
//*********************************
//Check for vaild email address.
//*********************************
if ($key == 'email'){
$email = filter_var($value, FILTER_VALIDATE_EMAIL) ? TRUE : FALSE;
$email_value = $value;
$email_array[] = $email;
}
//*********************************
//Check for empty string.
//*********************************
if ($key == 'empty'){
$empty_it = (trim($value) == FALSE) ? TRUE : FALSE;
$empty_array[] = $empty_it;
}
}
//********************************
//Check if you failed letters only.
//********************************
if ( count($letters_array) != count(array_filter($letters_array)) ) $errors .= 'You can only enter letters a-z or A-Z.<br />';
//********************************
//Check if you failed numbers only.
//********************************
if ( count($numbers_array) != count(array_filter($numbers_array)) ) $errors .= 'You can only enter numbers 0-9.<br />';
//*************************************
//Check if you failed email validation.
//*************************************
if ( count($email_array) != count(array_filter($email_array)) ) $errors .= 'You must enter a vaild e-mail address.<br />';
//*************************************
//Check if you empty string.
//*************************************
if ( count($empty_array) != count(array_filter($empty_array)) ) $errors .= 'You must enter a value for each required field.<br />';
//********************
//Display the errors.
//********************
if ($errors) echo '<h3>Oops..</h3>'. $errors; var_dump($args); die;
}
}
然后我这样称呼它:
$Validate->validate( array('empty' => $display_name, 'empty' => $password, 'empty' => $password_again,
'empty' => $gender, 'empty' => $month, 'empty' => $day, 'empty' => $year, 'email' => $email, 'letters' => $gender,
'numbers' => $month, 'numbers' => $day, 'numbers' => $year) );
但我的结果是这样的:
array(4) { ["empty"]=> string(4) "2013" ["email"]=> string(0) "" ["letters"]=> string(0) "" ["numbers"]=> string(4) "2013" }
有什么帮助吗?