实战jQuery跟PHP CodeIgniter表单验证
实战jQuery和PHP CodeIgniter表单验证
原文发表在 http://tech.it168.com/a2011/0818/1234/000001234617.shtml
上,乃本人作品,转载请注明:
前言
在Web建站中,表单的合法性验证是十分重要的一个环节,其中包括客户端浏览器的Javascript的验证和服务端的验证。在本文中将指导读者使用jQuery中的validate验证框架实现浏览器端的验证代码编写工作,validate框架是一个十分简单实用的验证框架,能大大提高客户端验证代码的的编写工作,同时,本文使用的是php中十分流行的CodeIgniter框架进行服务端的验证编写工作。本文阅读对象为对jQuery及对PHP CodeIgniter框架有一定认识的读者。
准备工作
我们必须下载CodeIgniter及jQuery,版本如下:
1.CodeIgniter 2.0.2(下载地址:http://codeigniter.com/downloads/)
2.jQuery 1.6.1 (下载地址:http://code.jquery.com/jquery-1.6.1.min.js)
3.jQuery validate框架,(下载地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation/)
设置CodeIgniter
我们需要自动加载url并且需要使用CodeIgniter中的form表单助手类,所以我们在应用的autoload.php中的第67行添加如下代码:
$autoload['helper'] = array('url', 'form');
建立视图层文件
接下来,我们开始编写页面的HTML页代码,我们将用户填写的表单命名为form_view,当校验成功提交后,如果没任何错误,则显示成功提示信息的页面命名为success_view,当然,我们先编写页面的头部和尾部的代码如下:
Views/common/Header.php:
在header.php中,我们引入了必须引入的jquery类库和jquery validate框架类库文件。
Views/common/footer.php
在form_view.php用户填写的表单页中,我们引入了CodeIgniter框架提供的表单助手类,
利用了其中的form_open标签,代码如下:
load->view('common/header'); ?>
'form');
echo form_open('form/process', $attributes); ?>
Form Validation with CodeIgniter and jQuery
Male
Female
load->view('common/footer'); ?>
Views/success_view.php
load->view('common/header'); ?>
Form was submitted successfully!
load->view('common/footer'); ?>
在显示成功页面中,只是简单显示一句成功提交的信息即可。
设置CSS
下面为了表单的美观,我们设置一下CSS,注意我们使用的是CSS3,代码如下:
body {
font-family: arial,verdana,sans-serif;
color:#333333;
font-size:13px;
margin: 0 auto;
background: #f5f5f5;
}
#wrapper {
margin: 0 auto;
position: relative;
background:#FFFFFF;
width: 900px;
border:10px solid #eaeaea;
}
#form {
padding: 10px;
}
#form .field {
margin-bottom:15px;
}
#form label{
display: block;
float: left;
font-weight: bold;
margin-right:10px;
text-align: right;
width: 120px;
line-height: 35px;
font-size:14px;
cursor: pointer;
}
#form .checkbox{
margin-top:10px;
}
#form .input{
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
background-color: #eaeaea;
background: -moz-linear-gradient(top, #ffffff, #f2f2f2);
background: -webkit-gradient(linear, left top, left bottom,
color-stop(0.0, #ffffff), color-stop(1.0, #f2f2f2));
border: 1px solid #cacaca;
font-family: inherit;
color: #797979;
font-size: 15px;
padding: 8px 10px;
width: 300px;
font-weight: bold;
}
#form .state{
border: 1px solid #b9bdc1;
padding: 5px;
font-size: 15px;
font-family: inherit;
font-weight: bold;
color: #797979;
}
#form :focus{
-webkit-box-shadow: 0px 0px 4px #aaa;
-moz-box-shadow: 0px 0px 4px #aaa;
box-shadow: 0px 0px 4px #aaa;
}
#form .gender-fields{
padding-top:10px;
}
#form span.error {
color:red;
padding-left:10px;
}
#form .info{
margin-left:130px;
font-size: 12px;
font-style:italic;
color: #999;
}
#form .submit{
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
font-family: arial,verdana,sans-serif;
background-color: #dedede;
background: -moz-linear-gradient(top, #ffffff, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom,
color-stop(0.0, #ffffff), color-stop(1.0, #eaeaea));
border: 1px solid #dedede;
color: #484848;
font-size:14px;
font-weight: bold;
padding: 8px 10px;
cursor: pointer;
margin-left:220px;
}
/*-- Table design to display data in success view --*/
#display_data{
padding:10px;
}
#display_data .name{
font-style: italic;
text-decoration:underline;
}
#display_data table{
border:1px solid #e5eff8;
margin:10px 0px;
border-collapse:collapse;
}
#display_data tr.even{
background:#f7fbff
}
#display_data tr.odd .title {
background:#f4f9fe;
}
#display_data td {
border-bottom:1px solid #e5eff8;
border-right:1px solid #e5eff8;
color:#678197;
padding:5px 8px;
}
#display_data td.title{
font-weight: bold;
width:100px;
text-align:right;
}
#display_data td.info{
font-style: italic;
width:200px;
}
#footer {
width:60%;
margin:20px auto;
}
编写CodeIgniter的控制层文件
接下来,我们要在CodeIgniter中编写控制层文件,以加载视图文件,将控制层文件命名为form.php,放在applications/controller文件夹中,代码为:
class Form extends CI_Controller {
public function index()
{
$this->load->view('form_view');
}
现在,我们已经可以看下表单的效果了,在浏览器中输入如下URL访问:
http://localhost/form_validation/index.php/form
即可看到如下图界面:

设置jQuery Validate插件进行验证
jQuery Validate插件设置了大量常见的验证规则,如验证email,电话,日期等。我们先看下如何定义设置jQuery Validate的验证规则,比如定义了两个规则,分别验证用户名和email:
email: {
required: true,
email: true
},
name: {
required: true,
minlength: 3,
maxlength:25,
},
其中,required属性设置为true,表明该字段需要进行验证。比如这里设置了名称字段需要验证,最小输入的长度为3,最长的长度为25。而如果我们要新增加自己的校验规则,比如要名称字段只能输入的是字母,则可以编写自己的校验方法,并且使用正则表达式,代码如下:
$.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Please enter only letters");
这里,通过addMethod方法,增加了一个名为lettersonly的校验方法,并且使用正则表达式。下面是完成的一个js校验文件,如下:
(document).ready(function() {
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Please enter only letters");
// validate contact form on keyup and submit
$("#form").validate({
//set the rules for the fild names
rules: {
name: {
required: true,
minlength: 3,
maxlength:25,
lettersonly: true
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5,
maxlength:15
},
gender : {
required :true
},
state : {
required :true
},
agree : {
required :true
},
},
//设置错误信息
messages: {
name: {
required: "Name is required..",
},
password: {
required: "Please provide a password.",
minlength: "Password must be at least 5 characters long",
maxlength: "Password can not be more than 15 characters"
},
email: "Valid email is required.",
agree: "You must agree to our terms.",
gender: "Gender is required",
state: "Select state"
},
//错误提示信息的放置位置
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
});
});
这里,通过设置messages来设置当用户填入非法数据时,要显示的提示信息,而errElement和errorPlacement中,则分别设置了当出现错误时,错误信息追加在页面上显示的位置
服务端CodeIgniter的验证
接下来,我们要编写服务端的验证。首先,我们要通过引入CodeIgniter中库文件的验证助手类,即:
$this -> load -> library( 'form_validation' );
然后设置验证规则,比如象名称字段,设置规则为:
$this -> form_validation -> set_rules( 'name', 'Name', 'trim|required|alpha|min_length[3]|max_length[25]' );
即名称字段必须为字母,最小长度为3,最大长度为25,该字段不能为空。
当服务端验证通过后,返回到成功页,验证失败后返回到失败提示信息页,如下:
if ( $this -> form_validation -> run() === FALSE )
{
$this -> load -> view( 'form_view' );
}
else
{
$this -> load -> view( 'success_view' );
}
显示表单的错误信息
我们再在表单的每个字段中,添加显示服务端验证的出错信息的代码,比如:
Name
CodeIgniter默认显示表单错误信息是用段落的形式,不大友好,我们修改下验证助手的设置方法,设置成在每个表单字段后,用进行分隔,即:
$this -> form_validation -> set_error_delimiters('', '');
在通过了客户端浏览器及服务端的双重验证后,就可以提交数据,保存到数据库了,我们这个例子中不保存到数据库,只是简单再次罗列出来,代码如下:
$this -> name = $this -> security -> xss_clean( $this -> input -> post( 'name' ) );
$this -> email = $this -> security -> xss_clean( $this -> input -> post( 'email' ));
//load the data
$data['name'] = $this -> name;
$data['password'] = $this -> password;
$this -> load -> vars( $data );
$this -> load -> view( 'success_view' );
注意这里,我们还调用了xss_clean方法防止跨站RSS攻击。
最后,完成的控制层代码如下:
application/controllers/form.php
class Form extends CI_Controller {
public function index()
{
$this->load->view('form_view');
}
public function process()
{
$this -> load -> library( 'form_validation' );
$this -> form_validation -> set_error_delimiters('', '');
$this -> form_validation -> set_rules( 'name', 'Name', 'trim|required|alpha|min_length[3]|max_length[15]' );
$this -> form_validation -> set_rules( 'password', 'Password', 'trim|required|min_length[4]|max_length[15]' );
$this -> form_validation -> set_rules( 'email', 'Email address', 'trim|required|valid_email' );
$this -> form_validation -> set_rules( 'gender', 'Gender', 'required' );
$this -> form_validation -> set_rules( 'state', 'State', 'required' );
$this -> form_validation -> set_rules( 'terms', 'Terms', 'required' );
//设置校验显示信息
$this -> form_validation -> set_message( 'min_length', 'Minimum length for %s is %s characters');
$this -> form_validation -> set_message( 'max_length', 'Maximum length for %s is %s characters');
if ( $this -> form_validation -> run() === FALSE )
{
$this -> load -> view( 'form_view' );
}
else
{
$this -> name = $this -> security -> xss_clean( $this -> input -> post( 'name' ) );
$this -> password = $this -> security -> xss_clean( $this -> input -> post( 'password' ) );
$this -> email = $this -> security -> xss_clean( $this -> input -> post( 'email' ));
$this -> gender = $this -> input -> post( 'gender' );
$this -> state = $this -> input -> post( 'state' );
$this -> terms = $this -> input -> post( 'terms' );
$data['name'] = $this -> name;
$data['password'] = $this -> password;
$data['email'] = $this -> email;
$data['gender'] = $this -> gender;
$data['state'] = $this -> state;
$data['terms'] = $this -> terms;
//load the data and success view.
$this -> load -> vars( $data );
$this -> load -> view( 'success_view' );
}
}
}
当用户的输入完全正确后,success_view的视图页面代码如下所示,显示用户输入的字段信息:
views/success_view.php
load->view('common/header'); ?>
Thank you,
Form was submitted successfully!
We have received following data:
Your name:
Email:
Password:
Gender:
State:
Terms:
load->view('common/footer'); ?>
最后,读者可以在这里(http://gazpo.com/gazpo-files/tut10-form/form_validation.zip)下载本文的代码。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible
