【问题标题】:Do not refresh page if there is error in form validation in codeigniter如果codeigniter中的表单验证有错误,不要刷新页面
【发布时间】:2020-05-19 03:15:42
【问题描述】:

我正在提交在代码点火器中具有多个字段和不同验证集的表单。当我们点击提交时,它会重定向并检查验证,如果有任何错误,会在不同的页面上返回给我。我不想使用 jquery 或 javascript。

index.php查看文件

<form id="credit_card_form" method="POST" action="/book/final">
    <input class="some_field" type="text" name="some_text" value="hello" />
    <input type="submit" value="Submit">
</form>

validate.php 控制器文件

function final_validate(){
   if(some_text is not good){
       $data['msg'] = "It's not good";
       $view = "index.php";
       $this->load->view($view,$data);
   }
}

因此,如果函数返回 false,则不应刷新页面。它应该返回消息。

【问题讨论】:

标签: php codeigniter validation


【解决方案1】:

在不刷新页面的情况下进行任何复杂输入验证的唯一方法是使用 javascript/ajax,如果由于某种原因您不想使用,则有两个选项

  1. 使用html attributes 进行基本输入验证,但我宁愿不依赖它

     // this will force the user to enter at least 1 character and maximum of 10
     <input class="some_field" type="text" name="some_text" value="hello" required maxlength="10"/>
    
  2. 刷新页面但保留用户输入的所有值并显示错误

      // show errors if they exist
      <?php if(isset($message)): ?>
           echo 'some error html' . $message. 'some error html';
      <?php endif; ?>
     // show previous value if it exists
    <input class="some_field" type="text" name="some_text" value="<?php $this->input->post('some_text') ? $this->input->post('some_text') : '' ?>" />
    <input type="submit" value="Submit">
    
    // backend
    // do this if validation fails
    $this->session->set_flashdata(['message' => 'Invalid data.']);
    

尽管您可以这样做,但我强烈建议您使用 javascript 进行客户端验证。

【讨论】:

  • CodeIgniter 中有set_value() 方法可以在验证失败后保留数据。请检查。
猜你喜欢
  • 2015-02-06
  • 1970-01-01
  • 2015-07-31
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 2014-03-04
  • 1970-01-01
  • 2011-09-22
相关资源
最近更新 更多