我正在使用CodeIgniter表单验证库。
示例视图:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
控制器
<?php
class Form extends CI_Controller {
function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
}
?>
在这种情况下,当我填写用户名,密码,确认密码和电子邮件留下空白,提交表单后,它得到一个错误的电子邮件要求。很好,但是在这种情况下,我的用户名,密码,确认密码字段也丢失了数据,所以在这种情况下,如果发生任何错误,请帮助我。
<input type="text" name="username" value=<?php echo $this->input->post("username");?> size="50" />
最后我找到了解决方案:
我们必须像这样在value形参中使用set_value():
<?php echo set_value('username'); ?>
最好的方法是通过Ajax post使用它。不需要混淆是否。
将您的表单代码替换为以下代码:
<form>
<h5>Username</h5>
<input type = "text" name = "username" value = "<?php if (validation_errors()) { echo set_value('username'); } ?>" size = "50" />
<h5>Password</h5>
<input type = "text" name = "password" value = "<?php if (validation_errors()) { echo set_value('password'); } ?>" size = "50" />
<h5>Password Confirm</h5>
<input type = "text" name = "passconf" value = "<?php if (validation_errors()) { echo set_value('passconf'); } ?>" size = "50" />
<h5>Email Address</h5>
<input type = "text" name = "email" value = "<?php if (validation_errors()) { echo set_value('email'); } ?>" size = "50" />
<div><input type = "submit" value = "Submit" /></div>
</form>
使用说明:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username');?>" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password');?>" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf');?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email');?>" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>