[英]Add error message to field with codeigniter form_validation
With Codeigniter you can validate forms with the form_validation library. 使用Codeigniter,您可以使用form_validation库来验证表单。 However I don't use this all the time but I like to use the form_error('fieldname')
function. 但是我并不是一直使用它,而是喜欢使用form_error('fieldname')
函数。
Is it possible to push a error message to a field manually without doing form_validation->run()
. 是否可以在不执行form_validation->run()
情况下将错误消息手动推送到字段。
不,该函数仅设计用于Form_validation库。
I found a Codeigniter way to add the functionality I want. 我找到了一种Codeigniter方式来添加所需的功能。 By extending the system/libraries/Form_validation.php
. 通过扩展system/libraries/Form_validation.php
。
First create file: application/libraries/MY_Form_validation.php
首先创建文件: application/libraries/MY_Form_validation.php
Then extend the CI_Form_validation
class: 然后扩展CI_Form_validation
类:
<?php
/**
* Created by PhpStorm.
* User: william
* Date: 02/02/2016
* Time: 22:56
*/
class MY_Form_validation extends CI_Form_validation{
/**
* set error message
*
* sets the error message associated with a particular field
*
* @param string $field Field name
* @param string $error Error message
*/
public function setError($field, $error){
$this->_field_data[$field]['error'] = $error;
}
}
Now you can use the form_validation->setError('fieldname','error')
to manualy set error messages: 现在,您可以使用form_validation->setError('fieldname','error')
设置错误消息:
class Test extends CI_Controller{
function index(){
$this->load->library('form_validation');
if (/* your validation outside of the form_validation */) {
$this->form_validation->setError('username', 'Invalid login credentials');
}
$this->load->view('test');
}
}
Note! 注意! Use this when you want to do some custom validation without using a callback 当您想执行一些自定义验证而不使用回调时,请使用此选项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.