Table of Contents
这是控制器的add方法
这是视图的
问题
回复内容:
结尾补充个例子说明
Home Backend Development PHP Tutorial ci框架中验证表单类

ci框架中验证表单类

Jun 06, 2016 pm 08:08 PM
php

这是控制器的add方法

      public function add(){
        //验证有效性
        $this->load->library('form_validation');
        //设置规则
         $this->form_validation->set_rules('title', '标题', 'required|max_length[10]');
         $this->form_validation->set_rules('content', '内容', 'required|max_length[150]');

         if ($this->form_validation->run() == false){

             $this->load->view('admin/blogc/add');
         }else{
             //进行数据插入
             $this->load->model('blogm','bm');
             $this->bm->insert();
              redirect('admin/blogc/add');
             
         }     
       }
Copy after login
Copy after login

这是视图的

       <form action="<?php echo site_url('admin/blogc/add')?>" method="post" id="myform" name="myform" enctype="multipart/form-data">
        <table class="insert-tab" width="100%">
            <tbody>
                
                <tr>
                    <th><i class="require-red">*</i>标题:</th>
                    <td>
                        <input class="common-text required" id="title" name="title" size="50" value="<?php echo set_value('title')?>" type="text">
                        <?php echo form_error('title',"<span style='color:red'>",'</span>');?>
                    </td>
                </tr>
                
                
                <tr>
                    <th>内容:</th>
                    <td><textarea name="content" class="common-textarea" id="content" cols="30" style="width: 98%;" rows="10"><?php echo set_value('content')?></textarea>
                    <?php echo form_error('content',"<p style='color:red'>",'</p>')?>
                    </td>
                 </tr>
              </tbody>
          </table>
     </form>
Copy after login
Copy after login

问题

为什么我第一次直接在浏览器中打入 index.php/admin/blog_c/add?
他走的是 $this->load->view('admin/blogc/add');
如果走这个说明他默认是false 但是如果是falsed第一次为什么不出现用户名不能为空 而是要提交才触发了 求大神解释

回复内容:

这是控制器的add方法

      public function add(){
        //验证有效性
        $this->load->library('form_validation');
        //设置规则
         $this->form_validation->set_rules('title', '标题', 'required|max_length[10]');
         $this->form_validation->set_rules('content', '内容', 'required|max_length[150]');

         if ($this->form_validation->run() == false){

             $this->load->view('admin/blogc/add');
         }else{
             //进行数据插入
             $this->load->model('blogm','bm');
             $this->bm->insert();
              redirect('admin/blogc/add');
             
         }     
       }
Copy after login
Copy after login

这是视图的

       <form action="<?php echo site_url('admin/blogc/add')?>" method="post" id="myform" name="myform" enctype="multipart/form-data">
        <table class="insert-tab" width="100%">
            <tbody>
                
                <tr>
                    <th><i class="require-red">*</i>标题:</th>
                    <td>
                        <input class="common-text required" id="title" name="title" size="50" value="<?php echo set_value('title')?>" type="text">
                        <?php echo form_error('title',"<span style='color:red'>",'</span>');?>
                    </td>
                </tr>
                
                
                <tr>
                    <th>内容:</th>
                    <td><textarea name="content" class="common-textarea" id="content" cols="30" style="width: 98%;" rows="10"><?php echo set_value('content')?></textarea>
                    <?php echo form_error('content',"<p style='color:red'>",'</p>')?>
                    </td>
                 </tr>
              </tbody>
          </table>
     </form>
Copy after login
Copy after login

问题

为什么我第一次直接在浏览器中打入 index.php/admin/blog_c/add?
他走的是 $this->load->view('admin/blogc/add');
如果走这个说明他默认是false 但是如果是falsed第一次为什么不出现用户名不能为空 而是要提交才触发了 求大神解释

我来回答这个问题,第一次打开肯定是加载你这个模板,为什么?因为你第一次打开的时候没有提交title和content这两个数据上来,在这里的验证规则:

<code>$this->form_validation->set_rules('title', '标题', 'required|max_length[10]');
$this->form_validation->set_rules('content', '内容', 'required|max_length[150]');</code>
Copy after login

里面有个required的验证规则,意思是不为空,那么你第一次加载这个add方法的时候,什么数据都没提交肯定为空,所以

<code>$this->form_validation->run()</code>
Copy after login

执行这个得到的结果为false,自然就是加载了admin/blogc/add这个模板。
而你这个用户名不为空或者是为空的这个提示跟这个函数

<code>form_error();</code>
Copy after login

以及验证的类form_validation有关,如果第一次验证没通过但是没有显示出错的话;那么分析其代码应该是:
form_validation这个验证类验证的是post提交上来的数据,而第一次压根都没提交,所以虽然为false,但是根本没有获取到数据,所以不报错。也就是说当你第二次提交空的时候,利用$_POST['title']或者$_POST['content']获取到有title和content提交,但是为空。但第一次get加载的时候,获取$_POST['title']或者是$_POST['content']根本都不存在,所以也没法去验证,直接返回false。如果要验证我这个猜想对不对,你自己去看validation验证类的源代码就一目了然。不过我的想法是八九不离十了。

结尾补充个例子说明

比如我叫你去吃饭,看到有两碗饭你才吃,看到有一碗饭你不吃,但是假设你去看到的是两个空碗,你怎么吃?这里就是所谓的第一次加载啥都没有,但是会返回false;你看到两碗你才吃,看到一碗你不吃,看到两碗你才吃,这是饭存在的情况下,为空提交就相当于是一碗饭,验证不通过,报false,然后提示错误原因,而第一次没有饭的情况根本就没考虑到,所以虽然是不吃,但是没错可报,就这么回事。当然,你可以把饭换成屎来增加印象。
ci框架中验证表单类

因为你第一次打开是 get请求,第二次是post请求。

恰恰相反,CI的确默认只能验证post请求,run()方法的第一段这么写的:

<code>// Do we even have any data to process?  Mm?
$validation_array = empty($this->validation_data) ? $_POST : $this->validation_data;
if (count($validation_array) === 0)
{
   return FALSE;
}
</code>
Copy after login

那么,我们可以在$this->validation_data上做文章,实际上CI提供了public function set_data(array $data)方法手动增加需要验证的数据:

<code>public function set_data(array $data)
    {
        if ( ! empty($data))
        {
            $this->validation_data = $data;
        }

        return $this;
    }
</code>
Copy after login

还是我的那句话:你第一次打开这个网址时是 get请求,第二次是post请求。而默认只会对post请求验证,除非你手动调用set_data()方法。

CI的这个验证,确实和常规的不同,正常都是先判断是不是post请求,然后再验证,而ci不需要,他默认是如果没有_POST请求数据则验证虽然为false但错误信息为空,注意这里错误信息为空,而不是提示参数不存在什么的。所以会出现你说的情况。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles