CodeIgniter - 验证空值 [英] CodeIgniter - validate empty value
问题描述
如何让CodeIgniter在不具有必需
规则但用户留空的字段上运行自定义规则?
How do I get CodeIgniter to run custom rules on fields which don't have the required
rule but the user left empty?
最好的办法是在字段中添加空格,如果字符串为空,然后添加
The best I can come up with is to add a space to the field if the string is empty, and then add a trim
rule -- but this feels hacky.
仅当另一个字段具有特定值时,才需要字段:
Field is required only if another field has a certain value:
// depends[another_field.some_val]
public function depends($str, $field){
list($post_key, $post_val)=explode('.', $field);
if($_POST[$post_key] == $post_val){
return $str != "";
}
return true;
}
示例规则#2
只有在数据库中存在正则表达式时才需要字段:
Example rule #2
Field is required only if a regex exists on the database:
// regex[table_name.col_name.some_val]
public function regex($str, $field){
list($table, $col, $post_val)=explode('.', $field);
// Grab the regex
$regex = $this->CI ->db
->limit(1)
->select($col)
->where($post_val, $_POST[$post_val])
->get($table)
->row($col);
return preg_match('/'.$regex.'/', $str) === 1;
}
推荐答案
你指出,你需要一个字段需要。那么,使用一个新规则:'keep_checking'来创建一个 required 字段。这样,您强制系统检查任何您想要的。我做了什么:
From the code, the problem you point out is that you NEED make a field required. Well, make a kind of required field with a new rule: 'keep_checking'. This way, you force the system to check whatever you want. What I did:
- 一个My_Form_validation类扩展系统核心类(所以,你不必触摸系统文件)。注意:不要忘记此文件位于
application / libraries
文件夹内 - 检查自定义规则keep_checking是否已设置。这将覆盖在设置required规则时不检查字段的行为(请参阅下面的代码)
- A My_Form_validation class which extends system core class (so, you won't have to touch system files). NOTE: Don't forget this file goes inside of
application/libraries
folder - Check if the custom rule 'keep_checking' is set. That will override the behaviour of not checking the fields when 'required' rule is set (See the code below)
最后一点,扩展Form_validation类,你将有一个地方放置你将一直使用的所有新的自定义规则XD
Last point, after extending the Form_validation class you'll have a place to put all your new custom rules you'll be using all the time, XD
class MY_Form_validation extends CI_Form_validation
{
public function __construct( $rules = array( ) ) {
parent::__construct( $rules );
}
protected function _execute($row, $rules, $postdata = NULL, $cycles = 0)
{
// If the $_POST data is an array we will run a recursive call
if (is_array($postdata))
{
foreach ($postdata as $key => $val)
{
$this->_execute($row, $rules, $val, $cycles);
$cycles++;
}
return;
}
// --------------------------------------------------------------------
// If the field is blank, but NOT required, no further tests are necessary
$callback = FALSE;
//====================================================================
// NEW ADDED RULE > 'keep_checking', will check all the rules even if
// the field is empty
//====================================================================
if ( ! in_array('required', $rules) AND is_null($postdata) AND ! in_array( 'keep_checking', $rules ) )
{
// Before we bail out, does the rule contain a callback?
if (preg_match("/(callback_\w+(\[.*?\])?)/", implode(' ', $rules), $match))
{
$callback = TRUE;
$rules = (array('1' => $match[1]));
}
else
{
return;
}
}
// --------------------------------------------------------------------
// Isset Test. Typically this rule will only apply to checkboxes.
//====================================================================
// NEW ADDED RULE > 'keep_checking', will check all the rules even if
// the field is empty
//====================================================================
if (is_null($postdata) AND $callback == FALSE && !in_array( 'keep_checking', $rules ))
{
if (in_array('isset', $rules, TRUE) OR in_array('required', $rules))
{
// Set the message type
$type = (in_array('required', $rules)) ? 'required' : 'isset';
if ( ! isset($this->_error_messages[$type]))
{
if (FALSE === ($line = $this->CI->lang->line($type)))
{
$line = 'The field was not set';
}
}
else
{
$line = $this->_error_messages[$type];
}
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']));
// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
if ( ! isset($this->_error_array[$row['field']]))
{
$this->_error_array[$row['field']] = $message;
}
}
return;
}
// --------------------------------------------------------------------
// Cycle through each rule and run it
foreach ($rules As $rule)
{
$_in_array = FALSE;
// We set the $postdata variable with the current data in our master array so that
// each cycle of the loop is dealing with the processed data from the last cycle
if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata']))
{
// We shouldn't need this safety, but just in case there isn't an array index
// associated with this cycle we'll bail out
if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles]))
{
continue;
}
$postdata = $this->_field_data[$row['field']]['postdata'][$cycles];
$_in_array = TRUE;
}
else
{
$postdata = $this->_field_data[$row['field']]['postdata'];
}
// --------------------------------------------------------------------
// Is the rule a callback?
$callback = FALSE;
if (substr($rule, 0, 9) == 'callback_')
{
$rule = substr($rule, 9);
$callback = TRUE;
}
// Strip the parameter (if exists) from the rule
// Rules can contain a parameter: max_length[5]
$param = FALSE;
if (preg_match("/(.*?)\[(.*)\]/", $rule, $match))
{
$rule = $match[1];
$param = $match[2];
}
// Call the function that corresponds to the rule
if ($callback === TRUE)
{
if ( ! method_exists($this->CI, $rule))
{
continue;
}
// Run the function and grab the result
$result = $this->CI->$rule($postdata, $param);
// Re-assign the result to the master data array
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
// If the field isn't required and we just processed a callback we'll move on...
if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE)
{
continue;
}
}
else
{
if ( ! method_exists($this, $rule))
{
// If our own wrapper function doesn't exist we see if a native PHP function does.
// Users can use any native PHP function call that has one param.
if (function_exists($rule))
{
$result = $rule($postdata);
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
}
else
{
log_message('debug', "Unable to find validation rule: ".$rule);
}
continue;
}
$result = $this->$rule($postdata, $param);
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
}
// Did the rule test negatively? If so, grab the error.
if ($result === FALSE)
{
if ( ! isset($this->_error_messages[$rule]))
{
if (FALSE === ($line = $this->CI->lang->line($rule)))
{
$line = 'Unable to access an error message corresponding to your field name.';
}
}
else
{
$line = $this->_error_messages[$rule];
}
// Is the parameter we are inserting into the error message the name
// of another field? If so we need to grab its "field label"
if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['label']))
{
$param = $this->_translate_fieldname($this->_field_data[$param]['label']);
}
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
if ( ! isset($this->_error_array[$row['field']]))
{
$this->_error_array[$row['field']] = $message;
}
return;
}
}
}
}
UPDATE :
复选框行避免继续检查。只需添加我添加的新行,它会工作。您必须将keep_checking规则添加到您要检查的任何字段:
Checkbox line was avoiding keep checking. Just add the new line I added, and it'll work. You have to add the keep_checking rule to any field you want to check:
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('welcome_message');
}
public function test()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'keep_checking|required');
$this->form_validation->set_rules('surname', 'Surname', 'keep_checking|is_numeric');
if ( $this->form_validation->run() ) {
} else {
$this->load->view('form');
}
}
}
.php
<form action="test" method="post">
<?php echo validation_errors(); ?>
<p>
Name: <input name="name">
</p>
<p>
Surname: <input name="surname">
</p>
<p>
<input type="submit" value="Send">
</p>
</form>
提交表单后,您将看到输入字段中的所有规则。最后一点,不要忘记MY_Form_validation位于libraries文件夹内。
After submit that form, you'll see as CI check all rules from the input fields. Last point, don't forget that MY_Form_validation goes inside of libraries folder
这篇关于CodeIgniter - 验证空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!