使用jQuery Validation驗證使用者輸入-4

by vivid 21. 九月 2016 17:32

.NET Magazine國際中文電子雜誌
作 者:許薰尹
審 稿:張智凱
文章編號: N160917502

出刊日期:2016/9/21
開發工具:Visual Studio 2015 Update 3

本文延續系列文章的第一篇《使用jQuery Validation驗證使用者輸入-1》、第二篇《使用jQuery Validation驗證使用者輸入-2》、第三篇《使用jQuery Validation驗證使用者輸入-2》的情境,來介紹jQuery Validation常用的驗證規則,包含跳過驗證、相依驗證、遠端驗證與自訂驗證。

跳過驗證

若在某些情況下要跳過驗證,某些情況滿足時需要驗證,這就需要寫一小段程式碼來達到目地。假設我們希望當使用者勾選「電話通知?」的核取方塊時,便需要驗證行動電話的資料不可為空白,也只能包含數字;若使用者不勾選「電話通知?」的核取方塊時,便跳過驗證動作。

參考以下範例程式碼,叫用validate()方法時,設定「ignore」規則,忽略掉有套用「bypass」類別的HTML項目的驗證動作。接著註冊了電話通知核取方塊的change事件,當選取到的核取方塊項目變動時,若目前核取方塊被選取時,利用removeClass()方法移除行動電話HTML項目「bypass」類別的套用;若目前核取方塊未選取時,利用addClass()方法套用「bypass」類別,請參考下列程式碼:

<!DOCTYPE html>
<html>
<head>
    <title>
        會員註冊系統
    </title>
    <link href="Content/StyleSheet.css" rel="stylesheet" />
</head>
<body>
    <h1>My會員註冊系統</h1>
    <form method="post" action="./Default.aspx" id="form1">
        <fieldset>
            <legend> 個人資料 </legend>
            <label for="txtAccount" id="lblAccount"> 使用者帳號 </label>
            <input name="txtAccount" type="text" id="txtAccount" />

            <br />
            <br />
            <label for="chkPhone" id="lblPhone"> 電話通知? </label>
            <input name="chkPhone" type="checkbox" id="chkPhone" />
            <br />
            <br />
            <label for="txtPhone" id="lblPhone"> 行動電話 </label>
            <input name="txtPhone" type="text" id="txtPhone" class="bypass" disabled />
            <br />
            <br />
            <input type="submit" name="btnRegister" value="註冊" id="btnRegister" />
        </fieldset>
    </form>
    <script src="Scripts/jquery-3.1.0.min.js"></script>
    <script src="Scripts/jquery.validate.min.js"></script>
    <script src="Scripts/messages_zh_TW.min.js"></script>
    <script>
        $(function () {

            $("#chkPhone").change(function () {
                if ($(this).is(":checked")) {
                    $('#txtPhone').removeClass('bypass');
                    $("#txtPhone").prop("disabled", false);
                }
                else {
                    $('#txtPhone').addClass('bypass');
                    $("#txtPhone").prop("disabled", true);

                }
                validator.resetForm();
            });
            $("#form1").validate({
                ignore: ".bypass",
                rules: {
                    txtPhone: {
                        required: true,
                        digits: true
                    }
                },
                messages: {

                    txtPhone: {
                        required: "電話號碼不可以為空白",
                        digits: "電話號碼只能是數字"
                    }
                }
            });
        });
    </script>
</body>
</html>

 

網頁執行時,當電話通知項目未選取時,不進行驗證,請參考下圖所示:

clip_image002

圖 1:電話通知項目未選取時不驗證。

網頁執行時,當電話通知項目選取時,若未輸入電話號碼,將顯示以下錯誤資訊,請參考下圖所示:

clip_image004

圖 2:動態套用驗證。

相依驗證-1

上面的例子也可以改用相依驗證的方式來達成。修改上例程式如下,設定行動電話的「required」驗證規則時,指定它的值是相依於核取方塊(chkPhone)的值是否勾選。執行結果同上例,當電話通知項目未選取時,不進行驗證;當電話通知項目選取時,若未輸入電話號碼,將顯示錯誤資訊,請參考下列程式碼:

<!DOCTYPE html>
<html>
<head>
    <title>
        會員註冊系統
    </title>
    <link href="Content/StyleSheet.css" rel="stylesheet" />
</head>
<body>
    <h1>My會員註冊系統</h1>
    <form method="post" action="./Default.aspx" id="form1">
        <fieldset>
            <legend> 個人資料 </legend>
            <label for="txtAccount" id="lblAccount"> 使用者帳號 </label>
            <input name="txtAccount" type="text" id="txtAccount" />

            <br />
            <br />
            <label for="chkPhone" id="lblNotify">電話通知?</label>
            <input name="chkPhone" type="checkbox" id="chkPhone" />
            <br />
            <br />
            <label for="txtPhone" id="lblPhone">行動電話</label>
            <input name="txtPhone" type="text" id="txtPhone" />
            <br />
            <br />
            <input type="submit" name="btnRegister" value="註冊" id="btnRegister" />
        </fieldset>
    </form>
    <script src="Scripts/jquery-3.1.0.min.js"></script>
    <script src="Scripts/jquery.validate.min.js"></script>
    <script src="Scripts/messages_zh_TW.min.js"></script>
    <script>
        $(function () {
            $("#form1").validate({
                rules: {
                    txtPhone: { required: "input[name=chkPhone]:checked" }
                },
                messages: {

                    txtPhone: {
                        required: "電話號碼不可以為空白"
                    }
                }
            });
         
        });
    </script>
</body>
</html>

 

相依驗證-2

若相依驗證的邏輯太複雜,可以將檢查邏輯包裝成一個方法,只要驗證成功,讓此方法回傳true;若驗證失敗,則讓這個方法回傳false,並將此方法指定給「depends」,參考以下範例程式碼,改寫上例,可達到相同的驗證效果,請參考下列程式碼:

<!DOCTYPE html>
<html>
<head>
    <title>
        會員註冊系統
    </title>
    <link href="Content/StyleSheet.css" rel="stylesheet" />
</head>
<body>
    <h1>My會員註冊系統</h1>
    <form method="post" action="./Default.aspx" id="form1">
        <fieldset>
            <legend> 個人資料 </legend>
            <label for="txtAccount" id="lblAccount"> 使用者帳號 </label>
            <input name="txtAccount" type="text" id="txtAccount" />

            <br />
            <br />
            <label for="chkPhone" id="lblNotify"> 電話通知? </label>
            <input name="chkPhone" type="checkbox" id="chkPhone" />
            <br />
            <br />
            <label for="txtPhone" id="lblPhone"> 行動電話 </label>
            <input name="txtPhone" type="text" id="txtPhone" />
            <br />
            <br />
            <input type="submit" name="btnRegister" value="註冊" id="btnRegister" />
        </fieldset>
    </form>
    <script src="Scripts/jquery-3.1.0.min.js"></script>
    <script src="Scripts/jquery.validate.min.js"></script>
    <script src="Scripts/messages_zh_TW.min.js"></script>
    <script>
        $(function () {
            $("#form1").validate({
                rules: {
                    txtPhone: {
                        required: {
                            depends: function () {
                                return $("#chkPhone").is(":checked");
                            }
                        }
                    }
                },
                messages: {
                    txtPhone: {
                        required: "電話號碼不可以為空白"
                    }
                }
            });
        });
    </script>
</body>
</html>

 

遠端驗證

有時驗證的動作要配合伺服端程式碼才能完成。例如註冊會員帳號時,若使用者輸入的帳號,已經存在於伺服端的資料庫,那麼便需要及時提示使用者帳號已存在的訊息,此時可以搭配remote驗證來完成這個功能。

首先伺服端需要寫個程式碼接收請求,並進行驗證的動作,舉例來說,以下範例程式碼,是一個使用ASP.NET Web Form撰寫的伺服端程式,檔名為CheckAccount.aspx,這個程式將檢查使用者傳入的txtAccount參數的值不可以是userList集合中的任一項目,若txtAccount參數的值包含在userList集合中,便代表帳號重複,使用Response.Write()方法送出「false」,代表驗證失敗;若txtAccount參數的值沒有包含在userList集合中,便代表帳號沒有重複,使用Response.Write()方法送出「true」,代表驗證成功。

請參考下列程式碼,為CheckAccount.aspx內容:

<%@ Page Language="C#" %>
<script runat="server">

  public static List<string> userList = new List<string>() {
    "MARY",
    "CANDY",
    "SINDY",
    "LILI"
  };

  protected void Page_Load(object sender, EventArgs e)
  {
      var user = Request.Params["txtAccount"].ToUpper();
      if (userList.IndexOf(user) >= 0)
      {
          Response.Write("false");
      }
      else
      {
          Response.Write("true");
      }
  }
</script>

 

網頁程式碼如下,設定remote要呼叫CheckAccount.aspx進驗證檢查,請參考下列程式碼:

 

<!DOCTYPE html>
<html>
<head>
    <title>
        會員註冊系統
    </title>
    <link href="Content/StyleSheet.css" rel="stylesheet" />
</head>
<body>
    <h1>My會員註冊系統</h1>
    <form method="post" action="./Default.aspx" id="form1">
        <fieldset>
            <legend> 個人資料 </legend>
            <label for="txtAccount" id="lblAccount"> 使用者帳號 </label>
            <input name="txtAccount" type="text" id="txtAccount" />
            <br />
            <br />

            <input type="submit" name="btnRegister" value="註冊" id="btnRegister" />
        </fieldset>
    </form>
    <script src="Scripts/jquery-3.1.0.min.js"></script>
    <script src="Scripts/jquery.validate.min.js"></script>
    <script src="Scripts/messages_zh_TW.min.js"></script>
    <script>
        $(function () {
            $("#form1").validate({
                rules: {
                    txtAccount: {
                        required: true,
                        minlength: 2,
                        maxlength: 20,
                        remote : "CheckAccount.aspx"
                    }
                },
                messages: {
                    txtAccount: {
                        required: "帳號不可以為空白",
                        maxlength: jQuery.validator.format("帳號最多只能{0}個字"),
                        remote: "帳號已存在"
                    }
                }
            });
        });
    </script>
</body>
</html>

網頁執行時,當帳號已存在於伺服器端,將顯示以下錯誤資訊,請參考下圖所示:

clip_image006

圖 3:遠端驗證。

自訂驗證

jQuery Validation也允許你自訂驗證的邏輯。定義的方式很簡單,將自訂的檢查邏輯包裝在一個方法之中,若驗證成功,讓方法回傳true;若驗證失敗,讓此方法回傳false,再設定驗證要採用此方法的規則。參考以下範例程式碼,使用$.validator.addMethod定義一個myvalidation方法,使用規則運算式檢查行動電話中不能包含任何文字,只能包含數字。並在rules中將myvalidation設定為true,請參考下列程式碼:

<!DOCTYPE html>
<html>
<head>
    <title>
        會員註冊系統
    </title>
    <link href="Content/StyleSheet.css" rel="stylesheet" />
</head>
<body>
    <h1>My會員註冊系統</h1>
    <form method="post" action="./Default.aspx" id="form1">
        <fieldset>
            <legend> 個人資料 </legend>
            <label for="txtAccount" id="lblAccount"> 使用者帳號 </label>
            <input name="txtAccount" type="text" id="txtAccount" />
            <br />
            <br />

            <label for="txtPhone" id="lblPhone">行動電話</label>
            <input name="txtPhone" type="text" id="txtPhone" />
            <br />
            <br />

            <input type="submit" name="btnRegister" value="註冊" id="btnRegister" />
        </fieldset>
    </form>
    <script src="Scripts/jquery-3.1.0.min.js"></script>
    <script src="Scripts/jquery.validate.min.js"></script>
    <script src="Scripts/messages_zh_TW.min.js"></script>
    <script>
        $(function () {
            $("#form1").validate({
                rules: {
                    txtPhone: {
                        required: true,
                        myvalidation: true
                    }
                }
            });
            $.validator.addMethod("myvalidation",
                function (value, element) {
                    return /^[0-9]+$/.test(value);
                },
                "行動電話中不能包含任何文字");
        });

    </script>
</body>
</html>

 

網頁執行時,當行動電話包含任意文字時,將顯示以下錯誤資訊,請參考下圖所示:

clip_image008

圖 4:自訂驗證。

Tags:

.NET Magazine國際中文電子雜誌 | ASP.NET | JavaScript | jQuery | 許薰尹Vivid Hsu

評論 (54) -

cours de theatre
cours de theatre United States
2017/10/1 上午 03:13:28 #

I truly appreciate this blog article.Really looking forward to read more. Fantastic.

回覆

nghi duong vung tau
nghi duong vung tau United States
2017/10/6 下午 11:21:12 #

Really enjoyed this article.Thanks Again. Will read on...

回覆

buy hacklink google
buy hacklink google United States
2017/10/9 下午 01:16:18 #

Very informative article. Cool.

回覆

kamagra
kamagra United States
2017/10/9 下午 02:54:04 #

I loved your article post.Really looking forward to read more. Keep writing.

回覆

can ho bien vung tau
can ho bien vung tau United States
2017/10/9 下午 05:10:44 #

Enjoyed every bit of your post.Really looking forward to read more. Will read on...

回覆

solarmovie
solarmovie United States
2017/10/10 下午 06:59:08 #

I loved your article post.Much thanks again. Cool.

回覆

Nathan Coombe
Nathan Coombe United States
2017/10/10 下午 09:05:48 #

I appreciate you sharing this blog post.Really looking forward to read more. Will read on...

回覆

pirater un compte facebook
pirater un compte facebook United States
2017/10/10 下午 11:24:26 #

Very neat blog.Thanks Again. Much obliged.

回覆

Buy illegal backlinks
Buy illegal backlinks United States
2017/10/12 下午 07:49:08 #

I appreciate you sharing this blog post.Really looking forward to read more. Really Great.

回覆

view
view United States
2017/10/14 下午 02:29:21 #

I really enjoy the post.Really thank you!

回覆

dragon city hack android 1
dragon city hack android 1 United States
2017/10/15 下午 02:31:00 #

Very neat article post.Really thank you! Great.

回覆

omega xl
omega xl United States
2017/10/15 下午 07:13:40 #

I really enjoy the blog post. Really Cool.

回覆

visit this website
visit this website United States
2017/10/17 下午 01:48:39 #

Thanks for sharing, this is a fantastic article. Great.

回覆

sletrokor review
sletrokor review United States
2017/10/17 下午 07:21:26 #

Thanks a lot for the article post.Thanks Again. Really Cool.

回覆

Calla Garden
Calla Garden United States
2017/10/19 上午 04:43:40 #

Thanks so much for the blog.

回覆

VigRx Plus
VigRx Plus United States
2017/10/19 上午 06:24:34 #

Very neat blog article.Really thank you! Cool.

回覆

check out here
check out here United States
2017/10/19 下午 05:12:54 #

Hey, thanks for the blog article.Much thanks again.

回覆

pure slim 1000 review
pure slim 1000 review United States
2017/10/20 上午 02:43:11 #

Awesome blog post.Thanks Again. Keep writing.

回覆

DIC Phoenix
DIC Phoenix United States
2017/10/21 上午 02:24:06 #

I loved your post.Really thank you! Awesome.

回覆

prix carte grise
prix carte grise United States
2017/10/21 上午 06:03:10 #

I really like and appreciate your article post.Really looking forward to read more. Keep writing.

回覆

elakekassa
elakekassa United States
2017/10/21 下午 04:27:38 #

Im grateful for the article post. Really Great.

回覆

website designing company in Delhi India
website designing company in Delhi India United States
2017/10/24 上午 08:56:19 #

Im grateful for the blog article.Really thank you! Much obliged.

回覆

can ho vung tau
can ho vung tau United States
2017/10/28 上午 09:02:08 #

Wow, great article post. Great.

回覆

EZ Battery Reconditioning Scam
EZ Battery Reconditioning Scam United States
2017/10/30 上午 07:55:03 #

I really like and appreciate your blog post.Really thank you! Much obliged.

回覆

informacje plock
informacje plock United States
2017/10/30 下午 03:40:59 #

I think this is a real great blog article.Really looking forward to read more. Much obliged.

回覆

mamaweeb
mamaweeb United States
2017/11/1 上午 08:09:29 #

Thanks-a-mundo for the blog. Much obliged.

回覆

phenocal
phenocal United States
2017/11/1 下午 03:33:22 #

Hey, thanks for the article post.Really looking forward to read more. Want more.

回覆

phentaslim
phentaslim United States
2017/11/3 上午 08:05:26 #

Thanks so much for the blog.Really thank you! Really Cool.

回覆

sciatica treatment for elderly
sciatica treatment for elderly United States
2017/11/15 上午 11:48:22 #

Very informative blog post.Really thank you! Great.

回覆

Great, thanks for sharing this blog.Much thanks again. Fantastic.

回覆

porno
porno United States
2017/12/1 下午 08:44:01 #

Major thankies for the blog.Really looking forward to read more. Will read on...

回覆

business trade lines
business trade lines United States
2017/12/3 上午 08:51:21 #

Thanks so much for the blog.Really looking forward to read more. Awesome.

回覆

free android porn
free android porn United States
2017/12/5 下午 01:42:06 #

Very good blog article.Thanks Again.

回覆

Im grateful for the blog article.Thanks Again. Much obliged.

回覆

A round of applause for your article post.Really looking forward to read more. Fantastic.

回覆

tips lose weight
tips lose weight United States
2017/12/17 上午 04:21:06 #

Major thankies for the post.Much thanks again. Will read on...

回覆

A big thank you for your post.Really thank you! Keep writing.

回覆

Processes
Processes United States
2017/12/17 下午 09:27:44 #

I am so grateful for your article post.Really thank you! Fantastic.

回覆

driver canon
driver canon United States
2017/12/23 上午 08:55:19 #

Im obliged for the post.Really looking forward to read more. Great.

回覆

Darwin Horan
Darwin Horan United States
2017/12/23 下午 07:23:01 #

I loved your post.Thanks Again. Fantastic.

回覆

Really enjoyed this article.Really looking forward to read more. Much obliged.

回覆

hp driver
hp driver United States
2017/12/25 下午 08:53:00 #

I truly appreciate this blog article. Will read on...

回覆

Enjoyed every bit of your blog article.Really looking forward to read more. Much obliged.

回覆

&#216;&#162;&#219;Œ&#217;†&#217;‡
آینه United States
2017/12/26 上午 08:43:44 #

Muchos Gracias for your blog.Really looking forward to read more. Really Cool.

回覆

SOCCER HIGHLIGHTS
SOCCER HIGHLIGHTS United States
2017/12/26 下午 04:18:00 #

Thanks for the post.Thanks Again. Really Great.

回覆

canon drivers
canon drivers United States
2017/12/27 下午 05:28:26 #

Enjoyed every bit of your blog article.Much thanks again. Will read on...

回覆

drivers hp
drivers hp United States
2018/1/2 上午 08:11:51 #

This is one awesome blog.Really looking forward to read more. Really Cool.

回覆

click over here
click over here United States
2018/1/2 下午 04:11:36 #

Looking forward to reading more. Great post.Really looking forward to read more. Want more.

回覆

Great blog.Really looking forward to read more. Really Cool.

回覆

hp drivers
hp drivers United States
2018/1/3 上午 07:32:35 #

I think this is a real great blog post.Really looking forward to read more. Much obliged.

回覆

mobile slots real money
mobile slots real money United States
2018/1/4 下午 06:08:27 #

Really informative blog.Much thanks again. Awesome.

回覆

hp driver
hp driver United States
2018/1/5 下午 08:11:49 #

Very neat blog article.Really looking forward to read more. Great.

回覆

FBA
FBA United States
2018/1/6 下午 12:16:13 #

Thank you for your blog.Much thanks again. Cool.

回覆

colocation miami
colocation miami United States
2018/1/10 上午 08:47:03 #

Major thanks for the article post.Much thanks again. Want more.

回覆

新增評論




  Country flag
biuquote
  • 評論
  • 線上預覽
Loading






NET Magazine國際中文電子雜誌

NET Magazine國際中文電子版雜誌,由恆逸資訊創立於2000,自發刊日起迄今已發行超過500篇.NET相關技術文章,擁有超過40000名註冊讀者群。NET Magazine國際中文電子版雜誌希望藉於電子雜誌與NET Developer達到共同學習與技術新知分享,歡迎每一位對.NET 技術有興趣的朋友們多多支持本雜誌,讓作者群們可以有持續性的動力繼續爬文。<請加入免費訂閱>

月分類Month List