CodeIgniter表单验证方法实例详解

时间:2022-11-18 13:23:16

本文实例讲述了CodeIgniter表单验证方法。分享给大家供大家参考,具体如下:

1.在D:\CodeIgniter\system\application\views目录下写一个视图文件myform.php

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
<head>
<title>My Form</title>
</head>
<body>
<?php echo $this->validation->error_string;?>
<?php echo form_open('form/index');?>
<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>

然后再写一个视图文件formsuccess.php

?
1
2
3
4
5
6
7
8
9
<html>
<head>
<title>My Form</title>
</head>
<body>
<h3>Your form was successfully submitted!</h3>
<p><?=anchor('form', 'Try it again!'); ?></p>
</body>
</html>

2.在D:\CodeIgniter\system\application\controllers目录下写一个控制器文件form.php

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
class Form extends Controller{
 function index(){
 $this->load->helper(array('form','url'));
 $this->load->library('validation');
   $rules['username'] = "required";
    $rules['password'] = "required";
    $rules['passconf'] = "required";
    $rules['email'] = "required";
    $this->validation->set_rules($rules);
 //    $this->validation->set_error_delimiters('<div class="error">','</div>');
 $fields['username'] = 'Username';
 $fields['password'] = 'Password';
 $fields['passconf'] = 'Password Confirmation';
 $fields['email'] = 'Email Address';
 $this->validation->set_fields($fields);
   if ($this->validation->run()==false) {
   $this->load->view('MyView/myform');
   }else {
   $this->load->view('MyView/formsuccess.php');
   }
 }
}
?>

3.http://localhost:8888/index.php/form/index访问一下

Ok,结果都出来了

希望本文所述对大家PHP程序设计有所帮助。