亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Ajax注冊(cè)用戶時(shí)實(shí)現(xiàn)表單驗(yàn)證

 更新時(shí)間:2021年03月07日 09:59:11   作者:JK_Rush  
這篇文章主要為大家詳細(xì)介紹了Ajax注冊(cè)用戶時(shí)實(shí)現(xiàn)表單驗(yàn)證,在網(wǎng)站上注冊(cè)時(shí),通常需要驗(yàn)證用戶名和電子郵件地址的可用性,本文將介紹如何實(shí)現(xiàn)表單驗(yàn)證功能

很多時(shí)候在網(wǎng)站上注冊(cè)時(shí),我們會(huì)發(fā)現(xiàn),注冊(cè)表單通常需要檢查用戶名和電子郵件地址的可用性;從而確保用戶之間不擁有相同的用戶名和電子郵件地址;一些網(wǎng)站喜歡在用戶提交填寫的用戶信息時(shí),做信息可用性的檢查,而一些網(wǎng)站會(huì)做實(shí)時(shí)的用戶名和電子郵件地址可用性檢查,例如:“用戶名”文本框失去焦點(diǎn)時(shí);就用戶體驗(yàn)來說,實(shí)時(shí)的用戶信息檢查用戶體驗(yàn)效果更好,而不是在表單提交后,告訴用戶信息不符合系統(tǒng)要求。

下面截圖是新浪微博的注冊(cè)界面,它采用的是實(shí)時(shí)的用戶信息檢查,如:手機(jī)號(hào)碼和用戶名等信息。

圖1新浪微博注冊(cè)表單

1、正文

假設(shè),現(xiàn)在要求我們實(shí)現(xiàn)一個(gè)注冊(cè)界面并且它采用實(shí)時(shí)方式檢查用戶信息是否符合系統(tǒng)的要求。

其中,注冊(cè)界面包含:用戶名,郵件地址,密碼和微博地址等信息;實(shí)時(shí)檢查:當(dāng)文本框失去焦點(diǎn)時(shí)對(duì)信息進(jìn)行實(shí)時(shí)檢查,例如:“用戶名”文本框失去焦點(diǎn)時(shí),觸發(fā)頁面發(fā)送Ajax請(qǐng)求,到數(shù)據(jù)庫(kù)中用戶是否可用,接著把查詢結(jié)果返回到前端頁面中。

對(duì)于表單輸入檢查,我們將使用前一博文《自定義jQuery插件Step by Step》中,自定義表單信息檢查插件對(duì)輸入信息進(jìn)行檢查。

圖2注冊(cè)驗(yàn)證過程

注冊(cè)表單設(shè)計(jì)

現(xiàn)在,讓我們定義注冊(cè)表單,它包含:用戶名,郵件地址,密碼和微博地址等信息,由于時(shí)間的關(guān)系,我們已經(jīng)把注冊(cè)表單界面的定義好了,具體實(shí)現(xiàn)代碼如下:

<body>
 <div id="Div1">
 <!-- Start Sign Up Form -->
 <form action="#signup-form" id="Form1">
 <h2>
 Sign Up</h2>
 <fieldset>
 <div class="fieldgroup">
 <label for="name">
 Name</label>
 <input class="form_element" type="text" name="name" validation="required nameAvailable" />
 <span class='availability_status'></span>
 </div>
 <div class="fieldgroup">
 <label for="email">
 Email</label>
 <input class="form_element" type="text" name="email" validation="email" />
 <span></span>
 </div>
 <div class="fieldgroup">
 <label for="password">
 Password</label>
 <input class="form_element" type="password" name="password" validation="password" />
 <span></span>
 </div>
 <div class="fieldgroup">
 <label for="weibo">
 Weibo</label>
 <input class="form_element" type="text" name="weibo" validation="url" />
 <span></span>
 </div>
 <div class="fieldgroup">
 <input type="submit" class="submit" value="Sign up">
 <span></span>
 </div>
 </fieldset>
 <div class="fieldgroup">
 <p>
 Already registered? <a >Sign in</a>.</p>
 </div>
 </form>
 <!-- End Sign Up Form -->
 </div>
</body>

上面,我們實(shí)現(xiàn)了注冊(cè)表單,它包含:用戶名,郵件地址,密碼和微博地址文本框,當(dāng)“用戶名”失去焦點(diǎn)時(shí),發(fā)送Ajax請(qǐng)求實(shí)時(shí)檢查用戶名是否可用,并且動(dòng)態(tài)地加載圖片表示檢查中和相應(yīng)的檢查結(jié)果。

圖3注冊(cè)表單

jQuery Validation插件

現(xiàn)在,我們需要修改一下前一博文中定義的表單檢查控件,需要增加用戶名檢查和文本框失去焦點(diǎn)事件(blur event)。

首先,我們?cè)赩alidation類型中,增加用戶名檢查方法,由于用戶檢查是通過發(fā)送Ajax請(qǐng)求,然后到數(shù)據(jù)庫(kù)中查詢是否存在該用戶名來確定該用戶名是否可用。

nameAvailable: {
 check: function(value) {

 if (value) {
 var dataString = 'username=' + value;
 var result;

 //&nbsp;Checking availability...
 // Loads checking image.
 $(".availability_status").html('<img src="loader.gif" align="absmiddle">');
 
 // 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 -"
}

上面,我們完成了在Validation類型中增加nameAvailable()方法,它通過發(fā)送異步Ajax請(qǐng)求來檢查用戶名是否可用,在檢查的過程中,在輸入框右邊動(dòng)態(tài)地加載圖片來表示檢查中,當(dāng)檢查結(jié)束加載相應(yīng)的圖片表示用戶是否可用。

接下來,我們將添加focus和blur事件,當(dāng)文本框得到焦點(diǎn)時(shí)觸發(fā)focus事件,提示輸入信息的要求,當(dāng)文本框失去焦點(diǎn)時(shí)觸發(fā)blur事件,發(fā)生實(shí)時(shí)Ajax請(qǐng)求,例如:檢查用戶名是否可用。

由于,事件方法應(yīng)該是Field類型公開的方法,確實(shí)我們也不想為每個(gè)Field對(duì)象都定義自己事件方法,所以我們通過原型鏈的方式公開事件方法focus()和blur(),具體實(shí)現(xiàn)如下:

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

我們給Field的原型鏈添加了事件響應(yīng)事件blur和focus,當(dāng)失去焦點(diǎn)時(shí)觸發(fā)Field的vlidate()方法,獲得焦點(diǎn)時(shí)觸發(fā)Field的hint()方法。

數(shù)據(jù)表設(shè)計(jì)

前面,我們提到注冊(cè)表單的用戶名可用性檢查設(shè)計(jì)是通過發(fā)送Ajax請(qǐng)求,然后到數(shù)據(jù)庫(kù)中查詢用戶名是否存在來確定用戶名的可用性。

接下來,我們添加數(shù)據(jù)庫(kù)表jk_user用來存儲(chǔ)用戶信息,它包括用戶名、密碼(注意:這里沒有考慮隱私信息的加密存儲(chǔ))、顯示名稱和注冊(cè)日期等,具體設(shè)計(jì)如下:

-- =============================================
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

圖4數(shù)據(jù)表設(shè)計(jì)

服務(wù)端設(shè)計(jì)

前面,我們實(shí)現(xiàn)了用戶表的設(shè)計(jì),由于注冊(cè)表單通過發(fā)送Ajax請(qǐng)求訪問服務(wù)器端公開的方法,然后通過該公開方法訪問數(shù)據(jù)庫(kù)。

接下來,我們定義用戶表(jk_user)的數(shù)據(jù)庫(kù)訪問對(duì)象(DAO),它包含方法IsAvailableUser()用來檢查用戶名是否可用,具體的實(shí)現(xiàn)如下:

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

現(xiàn)在,我們完成了數(shù)據(jù)庫(kù)訪問對(duì)象UserManager,它包含方法IsAvailableUser()來檢查用戶是否可用,如果該用戶名已經(jīng)存在返回false,反之返回true。

接下來,我們需要實(shí)現(xiàn)服務(wù)器端類UserService,讓客戶端通過它來調(diào)用UserManager中的IsAvailableUser()方法,首先我們創(chuàng)建一般處理程序(ASHX文件),實(shí)現(xiàn)ProcessRequest()方法,具體實(shí)現(xiàn)如下:

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

大家注意到UserService類實(shí)現(xiàn)了IHttpHandler接口,該接口包含一個(gè)方法ProcessRequest()方法和一個(gè)屬性IsReusable;ProcessRequest()方法用于處理入站的Http請(qǐng)求,在默認(rèn)情況下,UserService類把Response內(nèi)容類型定義為application/json,這樣我們就可以把數(shù)據(jù)通過JSON格式進(jìn)行傳輸;IsReusable屬性表示相同的處理程序是否可以用于多個(gè)請(qǐng)求,這里我們?cè)O(shè)置為true,那么處理程序可以用于多個(gè)請(qǐng)求。

前端實(shí)現(xiàn)

注冊(cè)表單在檢查用戶名時(shí)會(huì)在輸入框的右邊動(dòng)態(tài)地加載圖片,這里我們使用CSS Sprite技巧實(shí)現(xiàn)圖片的動(dòng)態(tài)加載。

當(dāng)頁面加載時(shí),不是加載每個(gè)單獨(dú)圖片,而是一次加載整個(gè)組合圖片。這是一個(gè)了不起的改進(jìn),因?yàn)槲覀冎恍璋l(fā)送一個(gè)HTTP請(qǐng)求獲取組合圖片就OK了,它大大減少了HTTP請(qǐng)求的次數(shù),減輕服務(wù)器壓力,同時(shí)縮短了懸停加載圖片所需要的時(shí)間延遲,使效果更流暢,不會(huì)停頓。

這里,我們使用可以一個(gè)在線的工具SpritePad設(shè)計(jì)組合圖片和生成相應(yīng)的CSS代碼。

圖5組合圖片

上面,我們已經(jīng)準(zhǔn)備好組合圖片了,接下來我們添加CSS代碼動(dòng)態(tài)加載“正確”和“出錯(cuò)”圖片,具體實(shí)現(xiàn)如下:

/*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;*/
}

接著,我們?cè)趎ameAvailable()方法中的Ajax方法添加文件“UserService.ashx”請(qǐng)求,并傳遞用戶名給服務(wù)器;在數(shù)據(jù)庫(kù)中查詢用戶名是否已經(jīng)存在,存在返回“false”,否則返回“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;
 }
 });

 }
});

最后,我們?cè)谧?cè)表單中添加調(diào)用自定義驗(yàn)證控件的jQuery代碼,具體實(shí)現(xiàn)如下:

<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>

圖6用戶注冊(cè)界面

如果大家還想深入學(xué)習(xí),可以點(diǎn)擊兩個(gè)精彩的專題:jquery表單驗(yàn)證大全 JavaScript表單驗(yàn)證大全

本文主要介紹了Ajax注冊(cè)表單的設(shè)計(jì),通過發(fā)送Ajax請(qǐng)求方式實(shí)時(shí)地檢查用戶名的可用性,并且使用了自定義的表單驗(yàn)證插件檢查輸入信息的正確性。

相關(guān)文章

最新評(píng)論