Learn jquery from scratch (11) Actual combat form verification and auto Completion prompt plugin _jquery

Source: Internet
Author: User
Tags curl documentation rowcount

I. Summary

This series of articles will take you into the wonderful world of jquery, with many authors ' specific experiences and solutions, even if you can use jquery to find some cheats in your reading.

This article is an introduction to the two most common jquery plug-ins. For form validation and AutoComplete prompts (similar to Google suggest).

Two. Foreword

Studying other people's work is a time-consuming and painful process. Of course, and my English is not relevant. Always feel that the control author wrote a lot of documents but not enough system, need to study a lot of examples to understand the author's thinking. So learning and researching a plugin requires a high cost, and if you find bugs and fix the costs, it's also unknown ( This time I spent less time solving a bug in Chinese that automatically completes the hint plugin, but if the complex bugs are not so simple.

For simple applications I first recommend the jquery UI above. But the jquery UI solves a limited problem. Using the jquery plugin is our last good way---is a good idea, at least better than our own development?

A lot of jquery's plug-in code is exceptionally beautiful, look at the Art Dragon home now the city input box control, in addition to the need to manually add many many attributes for the input box (onkeyup, onkeydown, etc.), but not universal, Consumes server resources and network resources. But it was also a work that took a long time to complete.

Standing on the shoulders of giants, it makes me feel like writing scripts and writing design C # programs, both have the height and depth to dig. In addition to using the features developed by authors, you can learn how to develop and encapsulate JavaScript controls. After reading the code and design ideas of a good jquery plugin author, the gap between the C # Programmer and the architect is often the difference between a design-level gap and an increase in the number of programmers who think of themselves as scripts.

I hope you will be able to learn how to encapsulate and design JavaScript controls in addition to how you can use the two plug-ins introduced in this chapter.

Three. Form verification plug-in Validate

You often validate user input before submitting a form. Asp. NET is used for this purpose and can be both client and server-side validation. However, validation controls are not used by all projects. And you often use your own client-side validation framework in an MVC project.

After comparing several form verification plug-ins, you decide to adopt the Validate plug-in. Because it is easy to use and flexible.

Plug-in home:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Plugin Documentation:

Http://docs.jquery.com/Plugins/Validation

Configuration Description:

Http://docs.jquery.com/Plugins/Validation/validate#options

1. Application examples

Instance effect:

Instance code:

<%@ Page language= "C #"%>

&lt;!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;Html xmlns= "Http://www.w3.org/1999/xhtml"&gt; &lt;Head Id= "Head1" Runat= "Server"&gt; &lt;Title&gt;JQuery PlugIn-Form validation plug-in instance Validate&lt;/Title&gt; &lt;!--black-tie,blitzer,blitzer,dot-luv,excite-bike,hot-sneaks,humanity,mint-choc,redmond,smoothness, South-street,start,swanky-purse,trontastic,ui-darkness,ui-lightness,vader--&gt; &lt;Link Rel= "stylesheet" Type= "Text/css" Href= "&lt;%=webconfig.resourceserver +"/Jslib/Jquery/Themes/Redmond/Style.Css"%&gt;" /&gt; &lt;Script Type= "Text/javascript" Src= "&lt;% =webconfig.resourceserver%&gt;/jslib/jquery/jquery-min-lastest.js"&gt;&lt;/Script&gt;&lt;script type="Text/javascript"Src="&lt;% =webconfig.resourceserver%&gt;/jslib/jquery/ui/jquery-ui-all-min-lastest.js"&gt;&lt;/script&gt; &lt;script type="Text/javascript"Src="&lt;% =webconfig.resourceserver%&gt;/jslib/jquery/plugin/jquery.validate/jquery.validate.min.js"&gt;&lt;/script&gt; &lt;script type="Text/javascript"Src="&lt;% =webconfig.resourceserver%&gt;/jslib/jquery/plugin/jquery.validate/localization/messages_cn.js"&gt;&lt;/script&gt; &lt;%If(False) {%&gt;&lt;script src="~/js/jquery-vsdoc-lastest.js"Type="Text/javascript"&gt;&lt;/script&gt; &lt;%}%&gt; &lt;script type="Text/javascript"&gt;/*========== must be placed in the header-loaded statement block. Try to avoid using ==========*/ &lt;/Script&gt;&lt;style type="Text/css"&gt; Body {font-size:12px;}/* The label of the text displayed in the form * *. slabel {width:100px; display:-moz-inline-box; line-height:1.8; display:inline-block; text-align:right;}/* ERROR Style * *Input.error, Textarea.error {border:solid 1px #CD0A0A;} label.error {color: #CD0A0A; margin-left:5px;}/* Deep red text * *. textred {color: #CD0A0A;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="Commentform"Method="Get"action=""&gt; &lt;fieldset style="width:500px;"&gt;&lt;legend&gt; Forms Validation &lt;/legend&gt; &lt;p&gt;&lt;labelFor="CNAME" Class="Slabel"&gt;&lt;emClass="Textred"&gt;*&lt;/em&gt; name:&lt;/label&gt; &lt;input id="CNAME"Name="Name"Size="25" Class="Required"Minlength="2"/&gt; &lt;/p&gt; &lt;p&gt;&lt;labelFor="Cemail" Class="Slabel"&gt;&lt;emClass="Textred"&gt;*&lt;/em&gt; e-mail:&lt;/label&gt; &lt;input id="Cemail"Name="Email"Size="25"/&gt; &lt;/p&gt; &lt;p&gt;&lt;labelFor="Curl" Class="Slabel"&gt; website:&lt;/label&gt; &lt;input id="Curl"Name="url"Size="25" Class="url"Value=""/&gt; &lt;/p&gt; &lt;p&gt;&lt;labelFor="Ccomment" Class="Slabel"&gt;&lt;emClass="Textred"&gt;*&lt;/em&gt; content:&lt;/label&gt; &lt;textarea rows="2"Id="Ccomment"Name="Comment"cols="20" Class="Required"style="height:80px;"&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;p style="Text-align:center;"&gt; &lt;inputClass="Submit"Type="Submit"Value=Submitted/&gt; &lt;/p&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;script type="Text/javascript"&gt;/*========== user-defined methods ==========*/ /*========== Event Binding ==========*/$(function() { });/*========== the statement executed when loading ==========*/$(function () {$ ( "#commentForm"). Validate ({errorclass: function (form) {//if you want to submit a form, you need to use Form.submit () instead of $ ( form). Submit () alert ( "submitted!");}, rules: {//adds two authentication methods for controls that have an email name: Required () and email () Email: {Required: true, email: true}}, messages: {//the required () and email () authentication method for the control with name for email email: {Required: "need to enter an email address", email:< span class= "str" > "e-mailbox format is incorrect"}}); }); </script> body> >               

2. Example explanation

(1) Verification method

The validation method is a Boolean value that verifies whether a control satisfies certain rules. For example, the email () method verifies that the content conforms to the email format and returns true if it matches. The following is the source code for the email method in the class library:

    Http://docs.jquery.com/Plugins/Validation/Methods/emailEmailfunction(value, Element) {Contributed by Scott gonzalez:http://projects.scottsplayground.com/email_address_validation/ Return This. Optional (Element) | | /^ (([a-z]|\d| [!#\$%&amp;'\*\+\-\/=\?\^_`{\|} ~]| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]) +(\. ([a-z]|\d| [!#\$%& ' \*\+\-\/=\?\^_ ' {\|} ~]| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]) +)*)| ((\x22) (((\x20|\x09) * (\x0d\x0a))? \x20|\x09) +)? ([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21| [\x23-\x5b]| [\x5d-\x7e]| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]) | (\ \ ([\x01-\x09\x0b\x0c\x0d-\x7f]| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]))) * (((\x20|\x09) * (\x0d\x0a))? (\x20|\x09) +)? (\x22))) @ (([a-z]|\d| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]) | ([a-z]|\d| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]) ([a-z]|\d|-|\.| _|~| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]) * ([a-z]|\d| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF])) \.) + ([a-z]| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]) | ([a-z]| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]) ([a-z]|\d|-|\.| _|~| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF]) * ([a-z]| [\U00A0-\UD7FF\UF900-\UFDCF\UFDF0-\UFFEF])) \.? $/i.test (value); },

We are:

Http://docs.jquery.com/Plugins/Validation

All of the built-in validation methods are listed in the list of built-in Validation methods section of. The plugin also provides a additional-methods.js file that contains more authentication methods, which can be enabled when introduced.

(2) Validation message

The validation message is the text that is displayed after the validation method fails. The validation message must be associated with one of the authentication methods, and the global validation message is saved in the JQuery.validator.messages property.

The default Validate class library has its own English-language authentication message:

  Messages: {
    "this field is required.",  
    //... }); 


This indicates that when the required validation method fails, the "This field is required" appears. This message.

In the download file localization folder, contains the Basic authentication message of each language, as this example introduces different language files to achieve language switching:

<script = "Text/javascript" src= "<% =webconfig.resourceserver %>/jslib/jquery/plugin/jquery.validate/localization/messages_cn.js "></ script>          



The contents of the language file are examples:

Jquery.extend (jQuery.validator.messages, {
    "required fields",
    //...});   

Now the required question prompt becomes Chinese.

In addition to the global default validation message, you can set specific validation messages for a single form element, such as the one in this article that has a unique validation message set for the email element:

        Messages: {
          //The required () and the email () authentication method for the control with the name email
          email: {Required:"e-mail Required", email :"e-mail format is not correct"}  

The Messages property of the options can set the validation message for a single form element, the first email represents the email element, the value is a collection, the required represents the required validation function, and the second email expression is the email validation function.

(3) Validation rules

The validation rule is the semantic statement: on element A, validation is done using validation method A and validation method B.

A validation rule associates an element with a validation method, because the validation method also associates the validation message, so the element is associated with the message.

There are several ways to add validation rules to an element.

The name element of this instance uses CSS style rules and element attribute rules:

<IDnamesizeclassminlength/>     

Class element property to set the CSS style class for the element, because the required class is added to the style class and is therefore associated with the required () validation function. This rule is called a CSS style rule.

MinLength element properties are also automatically associated with the minlength () validation function, which is called an element property rule.

There is also a programmatic way to associate:

        Rules: {
          //Add two authentication methods for the control with email for name: required () and email ()
          True}}, 

The above statement table name adds the required () and email () validation functions to the email form object.

(4) Form submission

By default, the form is not committed when the validation function fails.

However, you can allow the Submit button to skip validation by adding class= "Cancel" :

<typeclassnamevalue/>    


When the form is submitted, the function set by the Submithandler property in the options is triggered:

        function (form)
        {
          //If you want to submit a form, you need to use Form.submit () instead of $ (form). Submit () alert ("submitted!"); 

The signature of this function is ibid. In this function, we can write the business logic that needs to be processed before the form is submitted.

Note that when you finally programmatically submit a form, you must not use the Submit () method of the JQuery object, because this method touches the publish-order validation and calls the Submithandler-set function again, resulting in a recursive call.

The parameter form of this function is the form object, which is the purpose of submitting the form without validation: Form.submit ()

(5) Debug mode

In the development phase we usually do not want the form to actually commit, although it can be done by overriding the Submithandler function in this instance, but there is a better way that we can complete the formal submission logic in the Submithandler function, You can then set the Debug property of the options to achieve the purpose of not submitting the form even if validation passes:

$ (". Selector"). Validate ({
  true}) 

(6) Multi-form verification

Sometimes multiple form appears on a page because the validate control is packaged against the form object, so we can control which form objects need to be validated.

At the same time, the jquery.validator is provided for all the form objects that have the validate control applied on the page. The setdefaults function allows us to set all default values at once:

JQuery.validator.setDefaults ({ 
  true 
});

Four. Automatic completion of plug-in AutoComplete

AutoComplete Plug-ins can help us achieve the same effect as Google suggest:

Plug-in home:

http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/

Plugin Documentation:

Http://docs.jquery.com/Plugins/Autocomplete

Configuration Description:

Http://docs.jquery.com/Plugins/Autocomplete/autocomplete#toptions

1. Application examples

This example demonstrates the use of AutoComplete to complete the automatic prompt effect on the input city, as shown in figure:

Instance code:

&lt;%@ Page language= "C #"%&gt;

&lt;!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;Html xmlns= "Http://www.w3.org/1999/xhtml"&gt; &lt;Head Id= "Head1" Runat= "Server"&gt; &lt;Title&gt;JQuery PlugIn-Auto-complete Plug-in instance AutoComplete&lt;/Title&gt; &lt;!--black-tie,blitzer,blitzer,dot-luv,excite-bike,hot-sneaks,humanity,mint-choc,redmond,smoothness, South-street,start,swanky-purse,trontastic,ui-darkness,ui-lightness,vader--&gt; &lt;Link Rel= "stylesheet" Type= "Text/css" Href= "&lt;%=webconfig.resourceserver +"/Jslib/Jquery/Themes/Redmond/Style.Css"%&gt;" /&gt; &lt;Link Rel= "stylesheet" Type= "Text/css" Href= "&lt;%=webconfig.resourceserver +"/Jslib/Jquery/Plugin/Jquery.AutoComplete/Jquery.AutoComplete.Css"%&gt;" /&gt; &lt;Script Type= "Text/javascript" Src= "&lt;% =webconfig.resourceserver%&gt;/jslib/jquery/jquery-min-lastest.js"&gt;&lt;/Script&gt;&lt;script type="Text/javascript"Src="&lt;% =webconfig.resourceserver%&gt;/jslib/jquery/ui/jquery-ui-all-min-lastest.js"&gt;&lt;/script&gt; &lt;script type="Text/javascript"Src="&lt;% =webconfig.resourceserver%&gt;/jslib/jquery/plugin/jquery.autocomplete/jquery.autocomplete.min.js"&gt;&lt;/script&gt; &lt;%If(False) {%&gt;&lt;script src="~/js/jquery-vsdoc-lastest.js"Type="Text/javascript"&gt;&lt;/script&gt; &lt;%}%&gt; &lt;script type="Text/javascript"&gt;/*========== must be placed in the header-loaded statement block. Try to avoid using ==========*/ &lt;/Script&gt;&lt;style type="Text/css"&gt; Body {font-size:12px;} formlabel{Float: Left; width:150px; Text-align:right;} . forminput{Float: Left;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;!--Demo. Apply AutoComplete plugin--&gt; &lt;divClass="Ui-widget ui-widget-content Ui-corner-all"style="width:700px; padding:5px; "&gt; &lt;h3&gt; Demo. Application AutoComplete plugins &lt;/h3&gt; &lt;br style="Clear:both"/&gt; &lt;divClass="Formlabel"&gt; &lt;labelFor="Inputcityname"&gt; Please input city Pinyin and Chinese character:&lt;/label&gt; &lt;/div&gt; &lt;divClass="Forminput"&gt; &lt;input id="Inputcityname"Name="Inputcityname"Type="Text"/&gt; &lt;/div&gt; &lt;br style="Clear:both"/&gt; &lt;br style="Clear:both"/&gt; &lt;divClass="Formlabel"&gt; &lt;labelFor="Inputcityname"&gt; City id:&lt;/label&gt;&lt;/div&gt; &lt;divClass="Forminput"&gt; &lt;input id="Inputcityid"Name="Inputcityid"Type="Text"/&gt;&lt;/div&gt; &lt;br style="Clear:both"/&gt; &lt;br style="Clear:both"/&gt; &lt;/div&gt; &lt;script type="Text/javascript"&gt;/*========== user-defined methods ==========*/ City data VarCityList;AutoComplete options VarOptions = {minchars:1, max:500, width:250, Matchcontains:True, Formatitem:function(Row, I, max) {Returni +"/"+ Max +": \""+ row. Citynameen +"\" ["+ row. CityName +"]"; }, Formatmatch:function(Row, I, max) {ReturnRow. Citynameen +" "+ row. CityName; }, FormatResult:function(ROW) {ReturnRow. CityName; } };AutoComplete initialization function functionInitautocomplete (data) {citylist = data; $ ( "#inputCityName"). AutoComplete (citylist, Options); $ ( "#inputCityName"). Result (function (event, data, Formatted) {$ ( "#inputCityId"). Val (data. Elongcityid); }); } /*========== Event binding ==========*/$ (function () {}); /*========== the statement executed at load time ==========*/$ (function () {//load City data, The AutoComplete $.getjson is initialized with the returned data in the callback function (null, Initautocomplete)}); </script> body> >               

2. Example explanation

(1) Prepare the data source

The first thing to do is to implement the automatically recommended data source. This example gets the JSON object by sending an AJAX request. The AutoComplete () method supports two parameters, the first is data, and the second is options.

Where the data parameter can make one of the variables in this instance, or it can be a URL. If it is a URL, the AJAX request is invoked each time to fetch the data.

In order to be efficient I tend to use Ajax to get all the data after the page is loaded, and then use the PASS data variable to the AutoComplete component, when the amount of data allows. As shown in the example. Unless the data is extremely large and can no longer be loaded by the client, only partial data can be fetched from the server using the Send AJAX request each time. But this can be a burden on the server.

(2) Set key functions

Although options are optional, but for our data source citylist is a multiple attribute object, the following key configuration items must be set before they can be used:

Formatitem

Use this function to format each row of data that matches, and the return value is the content of the data that is displayed to the user.

Function Signature:

function (row, rownum, rowcount, Searchitem)

Parameter description:

Row: Current line. The results row,

RowNum: Current line number, starting from 1. (note is not an index, the index starts with 0) the position of the row in the list of results (starting at 1),

RowCount: Total Line No. The number of items in the list of results

Searchitem: The data used by the query, that is, the content of the data format returned by the Formatmatch function. In the Formatmatch function, we set the data format that is used in the internal search for the program, which is different from the data displayed to the user.

Formatmatch

Use this function for each row of data to format the data that you want to query. The return value is used for the internal search algorithm. The matching result that the user sees in the instance is the format that is set in Formatitem, but the inside of the program actually searches only the English and Chinese names of the city, the search data is defined in the Formatmatch:

"+ row." CityName;


Function Signature:

function (row, rownum, rowcount,)

Parameter Description ditto

FormatResult

This function is the data format returned by the user when it is selected. For example, only the city name is returned to the input control in an instance:

Return row. CityName;


Function Signature:

function (row, rownum, rowcount,)

Parameter Description ditto

(3) Add a result event function to a control

The above 3 functions do not implement this requirement: Although only the city name is returned, the city ID is used when querying, and the city ID needs to be stored in a hidden field after selecting a city.

So the AutoComplete control provides a result event function that triggers when a user selects an item:

      $ ("#inputCityName"). Result (function (event, data, formatted) {$ (    

Function Signature:

Function (event, data, formatted)

Parameter list:

The result event passes three parameters for the bound event handler function:

Event: Events object. Event.type for result.

Data: Selected rows.

Formatted: Although the official explanation should be the value returned by the FormatResult function, the result of the experiment is the value returned by Formatmatch. In this example: "Beijing Beijing".

(4) Matching Chinese

The current version of the AutoComplete control has a bug in Chinese search because its search events are bound to the KeyDown event and there is no hint when you enter the word "North" using the Chinese input method. I have made changes to the original library, the KeyDown event modified to KeyUp event, you can complete the Chinese intelligent prompt search. In addition, the main need to set the "Matchcontains" configuration item to "True", because our search format is "Beijing Beijing", the default matches only the beginning of characters.

(5) More Configuration items

For more configuration items, refer to the official documentation:

Http://docs.jquery.com/Plugins/Autocomplete/autocomplete#toptions

(6) More events

In addition to the AutoComplete () and result () functions described above, there are the following functions:

Search () : Activate Search event

Flushcache () : Empty Cache

setoptions (Options) : Set Configuration Items

Five. Summary

This article details the form verification plug-in and automatic plug-in, at present we can search a lot of plug-in applications, or thousands of plug-ins list, but could not find a detailed use of the document. Plug-in simple to use but the real flexible application is not easy, in addition to the English document to learn basic use, but also spend a long time to understand the role of various parameters, how to use and so on. And in the above two times the difficulty of development is relatively large, the core of the plug-in code is not commented and complex, in which to find a logical relationship to spend a lot of time and effort. This article describes the two plug-ins more details please refer to the official documentation, the address is in the beginning for everyone to provide.

Next article I decided to start with the jquery techniques and JavaScript essentials, we rarely develop custom plug-ins so the development of the plug-in chapter in the end.

This section code downloads: Http://xiazai.jb51.net/201101/yuanma/Code-jQueryStudy-11.rar

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.