Actual combat jquery and PHP codeigniter form verification

Source: Internet
Author: User
Tags autoload vars codeigniter contact form droplist
Practical jquery and PHP codeigniter form validation
Originally published in Http://tech.it168.com/a2011/0818/1234/000001234617.shtml
On, is my work, reproduced please specify:

Objective

In the Web site, the validation of forms is a very important part, including the client browser's JavaScript verification and service-side validation. In this article, we will instruct the reader to use the Validate validation framework in jquery to write the verification code of the browser side, the validate framework is a very simple and practical verification framework, which can greatly improve the writing of the client verification Code, and This article uses the very popular CodeIgniter framework in PHP for the validation of service-side writing. This article read about jquery and the PHP CodeIgniter framework have a certain understanding of the reader.

Preparatory work

We have to download CodeIgniter and jquery, and the versions are as follows:

1.CodeIgniter 2.0.2 (Download address: http://codeigniter.com/downloads/)

2.jQuery 1.6.1 (Download address: http://code.jquery.com/jquery-1.6.1.min.js)

3.jQuery Validate frame, (download address: http://bassistance.de/jquery-plugins/jquery-plugin-validation/)

Set CodeIgniter

We need to load the URL automatically and need to use the form helper class in CodeIgniter, so we add the following code to the 67th line in the app's autoload.php:

$autoload [' helper '] = array (' URL ', ' form ');
Create a view layer file

Next, we start to write the page's HTML page code, we have the user fill out the form named Form_view, when the validation is successfully submitted, if there is no error, the page showing the success message is named Success_view, of course, We first write the page's head and tail code as follows:

views/common/header.php:





<title>Form validation-gazpo.com</title>








In header.php, we introduced the JQuery class library and the jquery Validate Framework class library file that must be introduced.

views/common/footer.php


Tutorial by Gazpo.com.





In the form page that form_view.php users fill out, we introduced the form helper class provided by the CodeIgniter framework,

Using the Form_Open tag, the code is as follows:


Load->view (' Common/header ');?>


' form ');
echo form_open (' form/process ', $attributes);?>

Form Validation with CodeIgniter and JQuery




Name




Password




Email




Select Gender

Male
Female




Select State
Alabama Alaska Arizona



Terms







Load->view (' Common/footer ');?>
views/success_view.php


Load->view (' Common/header ');?>


Form was submitted successfully!




Load->view (' Common/footer ');?>
On the Display Success page, simply display a message that was successfully submitted.
Set CSS

Below for the appearance of the form, we set the CSS, note that we are using CSS3, the code is as follows:

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;

}
Writing CodeIgniter control-layer files

Next, we'll write the control-layer file in CodeIgniter to load the view file, name the control-layer file form.php, and place it in the Applications/controller folder with the following code:

Class Form extends Ci_controller {

Public Function Index ()

{

$this->load->view (' Form_view ');

}
Now that we can see the effect of the form, enter the following URL in the browser:

Http://localhost/form_validation/index.php/form

You can see the interface as follows:


Set up jquery Validate plugin for validation

The JQuery validate plugin sets up a number of common validation rules, such as verifying email, phone, date, etc. Let's take a look at how to define the validation rules for setting up jquery validate, such as defining two rules, verifying the user name and email separately:

Email: {

Required:true,

Email:true

},

Name: {

Required:true,

Minlength:3,

MAXLENGTH:25,

},


Where the required property is set to True, indicating that the field needs to be validated. For example, the Name field is set to verify that the minimum input length is 3 and the maximum length is 25. And if we want to add our own validation rules, such as the Name field can only enter the letter, you can write your own checksum method, and use regular expressions, the code is as follows:

$.validator.addmethod ("Lettersonly", function (value, Element) {

return this.optional (Element) | | /^[a-z]+$/i.test (value);

}, "Please enter only letters");


Here, a check method named Lettersonly is added with the Addmethod method, and a regular expression is used. The following is a complete JS checksum file, as follows:

(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

},

},

Setting error messages

Messages: {

Name: {

Required: "Name is required..",

},

Password: {

Required: "Please provide a password.",

MinLength: "Password must is at least 5 characters long",

MaxLength: "Password can not is more than characters"

},

Email: "Valid email is required.",

Agree: "You must agree to our terms."

Gender: "Gender is required",

State: ' Select State '

},

Where to place the error message

Errorelement: "Span",

Errorplacement:function (Error, Element) {

Error.appendto (Element.parent ());

}

});

});


Here, setting messages to set the message to display when the user fills in illegal data, and in Errelement and Errorplacement, respectively, sets the location where the error message is appended to the page when an error occurs.
Validation of service-side CodeIgniter

Next, we'll write the validation on the server side. First, we want to introduce the validation helper class for the library file in CodeIgniter, namely:

$this-Load library (' form_validation ');

Then set up validation rules such as the Name field and set the rule to:

Form_validation, Set_rules (' name ', ' name ', ' trim|required|alpha|min_length[3]|max_length[25 '), $this.

That is, the name field must be a letter, the minimum length is 3, and the maximum length is 25, the field cannot be empty.

When the service-side validation passes, return to the Success page, and then return to the failure prompt after the validation fails, as follows:

if ($this, Form_validation, run () = = = FALSE)

{

View (' Form_view '), load, $this

}

Else

{

View (' Success_view '), load, $this

}


Display error messages for a form

In each of the fields in the form, we add code that shows the error message for the server-side validation, such as:

Name

    

CodeIgniter default display form error message is in the form of paragraphs, not friendly, we modified the verification Assistant setting method, set to each form field after the separation, that is:

Form_validation, Set_error_delimiters, $this, (', ');

After the client browser and the service side of the two-step verification, you can submit data, saved to the database, we do not save to the database in this example, but simply again listed, the code is as follows:

$this, name = $this, security, Xss_clean ($this, input, post (' name '));

$this e-mail = $this, security---Xss_clean ($this, input, post (' email '));

Load the data

$data [' name '] = $this, name;

$data [' password '] = $this, password;

$this, Load, VARs ($data);

View (' Success_view '), load, $this


Note Here, we also call the Xss_clean method to prevent cross-site RSS attacks.

Finally, the completed control layer code is as follows:

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 ');

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

$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 ');

Setting the checksum display information

$this-Form_validation, Set_message (' min_length ', ' Minimum length for%s '%s characters ');

$this-Form_validation, Set_message (' max_length ', ' Maximum length for%s '%s characters ');

if ($this, Form_validation, run () = = = FALSE)

{

View (' Form_view '), load, $this

}

Else

{

$this, name = $this, security, Xss_clean ($this, input, post (' name '));

$this, password = xss_clean, security, $this ($this, input, post (' Password '));

$this e-mail = $this, security---Xss_clean ($this, input, post (' email '));

$this-gender = $this, Input-a post (' gender ');

$this, state = $this, Input-a post (' state ');

$this-terms = $this, input-a 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);

View (' Success_view '), load, $this

}

}

}
When the user's input is completely correct, the Success_view View page code shows the field information entered by the user as follows:

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 ');?>


Finally, the reader can download the code for this article here (http://gazpo.com/gazpo-files/tut10-form/form_validation.zip).
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.