Form Verification is implemented when Ajax registers users,

Source: Internet
Author: User

Form Verification is implemented when Ajax registers users,

Most of the time, when registering on the website, we will find that the registry list usually needs to check the availability of the user name and email address, so as to ensure that users do not have the same user name and email address; some websites like to check the information availability when users submit user information, while some websites will check the real-time user name and email address availability, for example: when the "user name" text box loses focus, in terms of user experience, real-time user information checks for better user experience, rather than telling users that information does not meet system requirements after the form is submitted.

The following is the Sina Weibo registration interface, which uses real-time user information checks, such as mobile phone numbers and user names.

Figure 1 Sina Weibo registry list

1. Text

Suppose that we need to implement a registration interface and check whether the user information meets the requirements of the system in real time.

The registration page contains the user name, email address, password, and Weibo address. Real-time check: when the text box loses focus, the information is checked in real time. For example: when the "user name" text box loses focus, the page is triggered to send an Ajax request to check whether the user in the database is available, and then the query result is returned to the front-end page.

For form input check, we will use the custom form information check plug-in the previous blog custom jQuery plugin Step by Step to check the input information.

Figure 2 registration verification process

Registry ticket Design
Now, let's define a registry ticket, which includes the username, email address, password, and Weibo address. Due to the time, we have defined the Registry ticket interface, the specific implementation code is as follows:

<body> <div id="Div1">  <!-- Start Sign Up Form -->  <form action="#signup-form" id="Form1">  

Above, we have implemented a registry ticket, which includes: user name, email address, password, and Weibo address text box. When the "user name" loses focus, the Ajax request is sent to check whether the user name is available in real time, and dynamically load the image to indicate the check and the corresponding check results.

Figure 3 Registration Form

JQuery Validation plug-in
Now, we need to modify the form check control defined in the previous blog. We need to add the user name check and the text box loss focus event (blur event ).

First, we add the user name check method in the Validation type. Because the User check is performed by sending an Ajax request and then querying the database to check whether the user name exists to determine whether the user name is available.

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 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;      }     });    }   });   // 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 -"}

In the preceding example, the nameAvailable () method is added to the Validation type. It sends an asynchronous Ajax request to check whether the user name is available. During the check, the image is dynamically loaded on the right of the input box to indicate the check. When the check ends, the corresponding image is loaded to indicate whether the user is available.

Next, we will add the focus and blur events. When the text box gets the focus, the focus event is triggered, prompting you to enter information requirements. When the text box loses the focus, the blur event is triggered and a real-time Ajax request occurs, for example, check whether the user name is available.

Because the event method should be a Field-type public method, we do not want to define our own event methods for each Field object, so we publish the event Method focus () through the prototype chain () and blur (), the specific implementation is 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 the validate method.  if (event == "blur") {   obj.field.bind("blur", function() {    return obj.validate();   });  }  // When field got focus, then invoked the hint method.  if (event == "focus") {   obj.field.bind("focus", function() {    return obj.hint();   });  } }}

We added the event RESPONSE event blur and focus to the Field prototype chain. when the focus is lost, the Field's vlidate () method is triggered, and the Field's hint () method is triggered when the focus is obtained.

Data Table Design
Previously, we mentioned that the user name availability check in the registry form is designed to determine the user name availability by sending an Ajax request and then querying the database for the existence of the user name.

Next, we add the database table jk_user to store user information, including the user name and password (Note: The encrypted storage of private information is not considered here), display name and registration date, etc, the specific design is as follows:

-- =============================================CREATE TABLE [dbo].[jk_users](  -- This is the reference to Users table, it is primary key. [ID] [bigint] IDENTITY(1,1) NOT NULL, [user_login] [varchar](60) NOT NULL, [user_pass] [varchar](64) NOT NULL, [user_nicename] [varchar](50) NOT NULL, [user_email] [varchar](100) 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](60) NOT NULL, [user_status] [int] NOT NULL CONSTRAINT [DF_jk_users_user_status] DEFAULT ((0)), [display_name] [varchar](250) NOT NULL) ajaxform2

Figure 4 Data Table Design

Server Design
Previously, we implemented the design of the User table, because the registry form sends an Ajax request to access the public method on the server side, and then accesses the database through this public method.

Next, we define the Database Access Object (DAO) of the User table (jk_user). The method IsAvailableUser () is used to check whether the user name is available. The specific implementation is as follows:

/// <summary>/// The user dao manager./// </summary>public class UserManager{ private const string Query = "SELECT user_login, user_email, user_url FROM 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 not, with specified username. /// </summary> /// <param name="userName">Name of the 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(ConfigurationManager.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 the IsAvailableUser () method to check whether the user is available. If the user name already exists, false is returned, and true is returned.

Next, we need to implement the server-side UserService class so that the client can use it to call the IsAvailableUser () method in UserManager. First, we create a general handler (ASHX file) and implement the ProcessRequest () method, the specific implementation is as follows:

/// <summary>/// The user availability check service./// </summary>public class 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  {   return true;  } }}

You have noticed that the UserService class implements the IHttpHandler interface, which contains a method ProcessRequest () method and an attribute IsReusable; ProcessRequest () method used to process Http requests of the inbound site. By default, the UserService class defines the Response content type as application/json, so that data can be transmitted in JSON format. The IsReusable attribute indicates whether the same handler can be used for multiple requests, if this parameter is set to true, the handler can be used for multiple requests.

Front-end implementation
When checking the user name in the registry list, images are dynamically loaded on the right side of the input box. Here we use the CSS Sprite technique to dynamically load images.

When a page is loaded, the entire combination of images is loaded at a time instead of each individual image. This is an amazing improvement, because we only need to send an HTTP request to obtain the combined image, which greatly reduces the number of HTTP requests and reduces the pressure on the server, at the same time, it shortens the time delay required for hovering and loading images, making the effect smoother without pausing.

Here, we can use an online tool SpritePad to Design Image combinations and generate the corresponding CSS code.

Figure 5 Combined images

As shown in the preceding figure, you are ready to combine images. Next, add the CSS code to dynamically load "correct" and "error" images. The specific implementation is 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;*/}

Then, add the file "UserService. request ashx and pass the user name to the server. If the user name already exists in the Database, "false" is returned; otherwise, "true" is returned ".

// 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 calls the custom verification control in the registry list. The specific implementation is as follows:

<script type="text/javascript"> // Sets display image size. pic = new Image(16, 16); 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 page

This article mainly introduces the design of Ajax registry form, checks the user name availability in real time by sending Ajax requests, and verifies the correctness of input information by using a custom form plugin.

Articles you may be interested in:
  • Asp ajax registration and verification to prevent spaces in user names
  • Use Jquery Ajax in Asp.net to detect User Registration (verify whether the user name is saved)
  • PHP + Ajax asynchronous communication Implements user name email verification (two methods)
  • Ajax verifies the registration name to check whether it exists in the Database
  • Use ajax to implement simple registration and verification of partial refresh instances
  • Details about real-time registration verification instances using jquery + ajax

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.