search
HomeBackend DevelopmentPHP Tutorialci框架中验证表单类

这是控制器的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');
             
         }     
       }

这是视图的

       <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>

问题

为什么我第一次直接在浏览器中打入 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');
             
         }     
       }

这是视图的

       <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>

问题

为什么我第一次直接在浏览器中打入 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>

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

<code>$this->form_validation->run()</code>

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

<code>form_error();</code>

以及验证的类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>

那么,我们可以在$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>

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

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

Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool