[英]Codeigniter, using Form validation for no POST data
我正在使用CodeIngiter创建一个宁静的应用程序。
我想知道是否可以对非$ _POST数据使用FormValidation类。
我在想:如果客户端以这种方式发送GET请求:
https://myrestapp.com/controller?firstValue=val&secondValue=val2
如何使用以下方法验证firstValue和secondValue:
//example
$this->form_validation->set_rules('firstValue', , 'required');
$this->form_validation->set_rules(secondValue, , 'required|integer');
并且,如何转换<?php echo validation_errors(); ?>
<?php echo validation_errors(); ?>
具有关联数组,例如array('firstValue' => "The field secondValue must be integer")
根据我的评论-您可以将关联数组传递给表单验证,而不是使用默认的$ _POST数组。
现在,您可以通过$this->form_validation->error_array()
获得表单验证错误数组。 您还可以自定义错误消息(留给您查找)
基于名为rest_app / rest_app?firstValue = val&secondValue = 2的控制器,索引方法可能看起来像这样-带有调试功能。
更改所需的内容,使其适合您的需求。 这只是一些演示代码。
public function index() {
$this->load->library('form_validation');
// Need to test this exists?
$str = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : NULL;
if ($str !== NULL) {
// Grab the Query string and turn it into an associative array
parse_str($str, $url_query_array);
// DEBUG - Check the array looks correct
var_dump($url_query_array);
// Give the form validation the fields/Values to work with.
$this->form_validation->set_data($url_query_array);
// Now for the Validation Rules
$this->form_validation->set_rules('firstValue', 'firstValue', 'required');
$this->form_validation->set_rules('secondValue', 'secondValue', 'required|integer');
// Did we get a valid
if ($this->form_validation->run()) {
echo "We got what we wanted, so do some stuff"; // DEBUG ONLY
// add your code here
} else {
echo "Well that didn't work well.";
$error_associative_array = $this->form_validation->error_array();
var_dump($error_associative_array); // DEBUG ONLY
// Send $error_associative_array back as a response
}
} else {
echo "No query string present";
// Handle this as an error condition or die silently.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.