Implement form validation _ajax related when Ajax registers user

Source: Internet
Author: User
Tags bind getdate http request

Many times when registering on a Web site, we find that the registration form usually needs to check the usability of the user name and email address, so that the user does not have the same username and e-mail address; some websites like to do information usability checks when users submit user information. Some websites do real-time user name and email address usability checks, such as when the "username" text box loses focus, and in the user experience, real-time user information checks the user experience better, rather than telling the user that the information does not conform to the system requirements after the form is submitted.

The screenshot below is the registration interface of Sina Weibo, which uses real-time user information inspection, such as mobile phone number and user name information.

Figure 1 Sina microblog registration form

1, the text

Suppose we now require that we implement a registration interface and that it uses real-time methods to check whether the user's information meets the requirements of the system.

Among them, the registration interface contains: username, email address, password and microblogging address information; Real time check: When the text box loses focus, the information is checked in real time, for example, when the "username" text box loses focus, the trigger page sends an AJAX request to the database to see if the user is available, The query results are then returned to the front-end page.

For form input checking, we will use the previous blog, custom jquery plug-in step by step, to check the input information by customizing the form information checking plug-in.

Figure 2 Registration verification process

Registration Form Design
Now, let us define the registration form, which contains: User name, email address, password and microblogging address, and so on, because of the time, we have the registration form interface has been defined, the implementation code is as follows:

<body> <div id= "Div1" > <!--Start Sign up Form--> <form action= "#signup-form" id= "Form1" > &L t;h2> Sign up 

Above, we implemented the registration form, which contains: username, email address, password and microblogging address text box, when "User name" lost focus, send Ajax request real-time check the user name is available, and dynamically load the picture represents the check and the corresponding inspection results.

Figure 3 Registration Form

JQuery Validation Plugin
Now, we need to modify the form checking controls defined in the previous blog, and we need to increase the user name check and the text box lose Focus event (Blur).

First, we increase the username checking method in the validation type, because the user checks to determine whether the user name is available by sending an AJAX request and then querying the database for the existence of the username.

Nameavailable: {check:function (value) {if (value) {var datastring = ' username= ' + value;

 var result;
  checking availability ...//loads Checking image.
 
 $ (". Availability_status"). html ('  ');
 Sends Ajax request to check the name is available or not. $.ajax ({type: ' Get ', url: ' userservice.ashx ', data:datastring, success:function (data) {//when the checking COM
 pleted, then loaded corresponding CSS style. $ ('. Availability_status '). Ajaxcomplete (function (event, request, Settings) {if (data = = False) {$ ('. Availability_statu
 S '). html (');
 $ ('. Availability_status '). Removeclass (' tick ');
 $ ('. Availability_status '). addclass (' error ');
 return true;
 } else {$ ('. Availability_status '). html (');
 $ ('. Availability_status '). Removeclass (' error ');

 $ ('. Availability_status '). addclass (' tick ');
 return false;

 }
 });

 }
 });
 Sends a Asyn reqeust, return false temporary.
 return false;
 E.preventdefault (); }
 else {$ ('. Availability_status '). Removeclass (' tick ');
 $ ('. Availability_status '). Removeclass (' error ');
 return false;

 }, Msg: "", Tip: "Should enter 4-30 characters, support letter, figures and _ or-"}

Above, we have completed the addition of the Nameavailable () method in the validation type, which checks whether the user name is available by sending an asynchronous Ajax request, and dynamically loads the picture on the right of the input box during the inspection to indicate the check. When the check finishes loading the corresponding picture indicates whether the user is available.

Next, we'll add the focus and blur events, triggering the focal event when the text box is focused, prompting for information, triggering a blur event when the text box loses focus, and a real-time Ajax request, such as checking that the user name is available.

Since the event method should be a method exposed by the field type, and indeed we do not want to define our own event methods for each Field object, we expose the event method focus () and Blur () through the way of the prototype chain, which is implemented as follows:

The prototype of Field type.
Field.prototype = {

 //public method.
 Attach:function (event) {

 //The object refers to Field object.
 var obj = this;
 When field lost focus, then invoked is the Validate method.
 if (event = = "Blur") {
 obj.field.bind ("Blur", function () {return
 obj.validate ();
 })
 ;

 When field got focus, then invoked is the hint method.
 if (event = = "Focus") {
 obj.field.bind (' Focus ', function () {return
 obj.hint ();
 })
 ;
}}}

We have added event response events Blur and focus to the prototype chain of field, triggering the field's Vlidate () method when the focal point is lost, and the hint () method that triggers the field when the focus is obtained.

Data table Design
Earlier, we mentioned that the user name usability check for the registration form is designed to determine the availability of the user name by sending an AJAX request and then querying the database to see if the user name exists.

Next, we add the database table Jk_user to store user information, which includes user name, password (note: There is no privacy information to consider the encrypted storage), display name and registration date, etc., specifically designed as follows:

--=============================================
CREATE TABLE [dbo]. [Jk_users] (
 --This is the reference to Users table and it is primary key.
 [ID] [bigint] IDENTITY (1,1) not NULL,
 [user_login] [varchar] (a) not null,
 [user_pass] [varchar] (?) not null,< C8/>[user_nicename] [varchar] (x) not NULL,
 [user_email] [varchar] (m) not NULL,
 [user_url] [varchar] (100) Not NULL,--This field get the

 default from function GETDATE ().
 [User_registered] [DateTime] Not NULL CONSTRAINT [df_jk_users_user_registered] DEFAULT (getdate ()),
 [User_activation_key] [varchar] (a) not NULL,
 [user_status] [int] NOT NULL CONSTRAINT [Df_jk_users_user_status] DEFAULT ((0)),
 [Display_name] [ VARCHAR] (not NULL
)
 Ajaxform2

Fig. 4 Data table Design

Service-Side design
Earlier, we implemented the user table design, because the registration form accesses the database by sending an AJAX request to access the method exposed by the server side, and then through that exposed method.

Next, we define the database Access object (DAO) for the user table (Jk_user), which contains the method Isavailableuser () to check that the user name is available, as follows:

<summary>///the user DAO Manager. </summary> public class Usermanager {Private Const string Query = "Select User_login, User_email, User_url FRO

 M jk_users WHERE (user_login = @user_login) ";
 <summary>///Initializes a new instance of the <see cref= "Usermanager"/> class. </summary> public Usermanager () {}///<summary>///Determines whether the user is available or no
 T, with specified username. </summary>///<param name= "UserName" >name of user.</param>///<returns>///<c> true</c> if is available user;
 otherwise, <c>false</c> </returns> public bool Isavailableuser (string userName) {using (var con = new SqlConnection (Configurationman Ager. connectionstrings["SQLCONN2"]. 
 ToString ())) using (var com = new SqlCommand (Query, con)) {//pass user_login parameter to SQL statement. Com. Parameters.Add ("@user_login", SqlDbType.VarChar). Value = UsernaMe Com.
 Connection.Open (); Return!com. ExecuteReader ().
 HasRows;

 }
 }
}

Now we have completed the database Access Object Usermanager, which contains method Isavailableuser () to check if the user is available, and returns true if the username already exists.

Next, we need to implement the server-side class UserService, let the client through it to invoke the Isavailableuser () method in Usermanager, first we create a generic handler (ashx file), implement ProcessRequest () method, specifically implemented as follows:

///<summary>///the user Availability Check service.///</summary> public C
 Lass Userservice:ihttphandler {public void ProcessRequest (HttpContext context) {//Response JSON type. Context.
 Response.ContentType = "Application/json"; Context.

 Response.Charset = "Utf-8";

 var manager = new Usermanager (); String userName = context.

 request.querystring["username"];
 Checks the username empty or not. if (string.
 IsNullOrEmpty (UserName)) {throw new Exception ("UserName can ' t be empty");
 }//Invokes the Isavailableuser method. var result = Manager.

 Isavailableuser (UserName); 
 Serializes data to JSON format. var json = new DataContractJsonSerializer (result.
 GetType ()); Json. WriteObject (context.
 Response.outputstream, result);
 }//Whether can resuable by other handler or not.
 public bool IsReusable {get {true; }
 }
}

It is noted that the UserService class implements the IHttpHandler interface, which contains a method ProcessRequest () method and a property Isreusable;processrequest () method for processing inbound HTTP requests. By default, the UserService class defines the response content type as Application/json so that we can transfer the data through the JSON format, and the IsReusable property indicates whether the same handler can be used for multiple requests. Here we set to True, then the handler can be used for multiple requests.

Front-End implementation
The registration form checks the user name to dynamically load the picture on the right side of the input box, where we use CSS sprite techniques to implement the dynamic loading of the picture.

When the page loads, instead of loading each individual picture, it loads the entire composite picture at a time. This is a terrific improvement, because we just send an HTTP request to get the combined picture OK, it greatly reduces the number of HTTP requests, reduce server pressure, while shortening the hover load picture required time delay, so that the effect is smoother and will not pause.

Here, we use an online tool spritepad to design the combined picture and generate the corresponding CSS code.

Figure 5 Combining pictures

Above, we are ready to combine the picture, next we add CSS code dynamically load "correct" and "error" picture, specifically implemented as follows:

/*css sprite*/
/*loads tick picture*/
. Tick
{
 width:17px;
 height:17px;
 margin:6px 0 0;
 Float:right;
 Background:url (.. /images/tipicon.png);
 background-position:0px-32px;
 Display:block;
 /*text-decoration:none;
 vertical-align:middle;*/
}

/*loads error picture*/
span.error
{
 width:17px;
 height:17px;
 margin:6px 0 0;
 Float:right;
 Background:url (.. /images/tipicon.png);
 background-position:0px-15px;
 Display:block;
 /*text-decoration:none;
 vertical-align:middle;*/
}

Next, we add the file "Userservice.ashx" request to the Ajax method in the Nameavailable () method, and pass the username to the server, query the database for the existence of the user name, and return "false", otherwise return "true".

Sends Ajax request to check the name is available or not.
$.ajax ({
 type: "Get",
 URL: "Userservice.ashx",
 data:datastring,
 success:function (data) {

 // When the checking completed, then loaded corresponding CSS style.
 $ ('. Availability_status '). Ajaxcomplete (function (event, request, settings) {
 if (data = = False) {
 $ ('. Availability_status '). html (');
 $ ('. Availability_status '). Removeclass (' tick ');
 $ ('. Availability_status '). addclass (' error ');
 return true;
 }
 else {
 $ ('. Availability_status '). html (');
 $ ('. Availability_status '). Removeclass (' error ');
 $ ('. Availability_status '). addclass (' tick ');
 return false;}});


Finally, we add the jquery code that invokes the custom validation control in the registration form, which is specifically implemented as follows:

<script type= "Text/javascript" >

 //Sets display image size.
 pic = new Image (in);
 PIC.SRC = "Loader.gif";

 $ (function () {//JQuery DOM ready function.

 Get the Form object.
 var signupform = $ ("#signup-form");

 Invokes the validation method.
 Signupform.validation ();

 });
</script>

Figure 6 User Registration interface

If you still want to learn more, you can click on two wonderful topics: jquery form verification Encyclopedia JavaScript form Verification Encyclopedia

This article mainly introduces the design of the Ajax registration form, checks the usability of the username in real time by sending the AJAX request, and uses the custom form verification plug-in to check the correctness of the input information.

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.