Asp.net MVC中表單驗證

iDotNetSpace發表於2009-02-16
在Asp.net MVC 中,View中我們仍然需要對提交的表單進行驗證。通常驗證分為客戶端驗證,服務端驗證。
客戶端驗證,我們可以使用JQuery validation plugin,服務端驗證,除了使用ModelState屬性顯示錯誤資訊到
View,還可以使用Fluent Validation for .NET,一個小巧的.net驗證框架,使用fluent的介面和lambda表示式對
你的業務物件構建驗證規則。而且也有對應的MVC擴充套件。
     我們首先增加一個驗證UserEntity的驗證類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DemoMVCForm.Models;
using FluentValidation;
using FluentValidation.Validators;

namespace DemoMVCForm.
{
    /// 
    /// UserValidation
    /// 
    /// Author : PetterLiu 2009-02-1515:54  http://wintersun.cnblogs.com 
    public class UserValidation : AbstractValidator<UserEntity>
    {
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// Author : PetterLiu 2009-02-1515:54  http://wintersun.cnblogs.com 
        public UserValidation()
        {
            RuleFor(u => u.UserName).NotEmpty();
            RuleFor(u => u.UserName).Length(5, 16);
            RuleFor(u => u.Password).NotEmpty().WithMessage("必須輸入密碼");
            RuleFor(u => u.Email).NotEmpty();
            RuleFor(u => u.Email).EmailAddress();
            RuleFor(u => u.Url).Url();
            RuleFor(u => u.PassportID).NotEmpty();
        }
    }

    /// 
    ///  UrlValidationRule
    /// 
    /// T
    /// Author : PetterLiu 2009-02-1515:54  http://wintersun.cnblogs.com 
    public class UrlValidationRule : RegularExpressionValidator
    {
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// Author : PetterLiu 2009-02-1515:54  http://wintersun.cnblogs.com 
        public UrlValidationRule()
            : base(@"^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$")
        {

        }
    }

    /// 
    /// UrlValidationExtension
    /// 
    /// Author : PetterLiu 2009-02-1515:54  http://wintersun.cnblogs.com 
    public static class UrlValidationExtension
    {
        public static IRuleBuilderOptionsstring> Url(this IRuleBuilderstring> ruleBuilder)
        {
            return ruleBuilder.SetValidator(new UrlValidationRule());
        }
    }
}

看上增加了服務端驗證規則多麼簡單的程式碼,比較直觀。後又增加一個驗證URL的規則,用於驗證輸入的URL。
接著來看,如何使用它:
/// 
/// Registers the specified user.
/// 
/// The user.
/// 
/// Author : PetterLiu 2009-02-1515:56  http://wintersun.cnblogs.com 
public JsonResult Register(UserEntity user)
{
    UserValidation userValidation = new UserValidation();
    ValidationResult validationResult = userValidation.Validate(user);

    //add error state information to ModelState.
    validationResult.AddToModelState(ModelState, "user");

    bool validationSucceeded = validationResult.IsValid;
    IList<ValidationFailure> failures = validationResult.Errors;
   
    //return result for json format.
    return Json(failures);
}
通過擴充套件的AddToModelState方法,能讓驗證的錯誤資訊返回VIEW,但實際上如果沒有使用Html.ValidationMessage,
也不需要這個方法了。看實際情況選擇了。最後把驗證後的結果物件:ValidationFarilure通過Json格式返回。
好,來看VIEW:
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Demotitle>
    <style. type="text/css">
        #inputArea
        {
            font-family: Arial, Sans-Serif;
        }
        #inputArea input, #inputArea textarea
        {
            font-family: Arial, Sans-Serif;
            margin-bottom: 5px;
            padding: 1px;
            border: solid 1px #85b1de;
        }
    style>
    <link href="http://www.cnblogs.com/Content/Site.css" rel="stylesheet" type="text/css" />

    <script. src="http://www.cnblogs.com/Scripts/jquery-1.3.1.js" type="text/javascript">script>

    <script. src="http://www.cnblogs.com/Scripts/jquery.validate.js" type="text/javascript">script>

    <script. src="http://www.cnblogs.com/Scripts/jquery.form.js" type="text/javascript">script>

    <script. type="text/javascript">
        $(document).ready(function() {
            function ProcessJson(data) {
                var ret = "伺服器返回驗證結果:\n"
                for (key in data) {
                    ret += data[key].ErrorMessage;
                    ret += "\n";
                }
                alert(ret);
            }
            jQuery.validator.addMethod("usernamecheck", function(value, element) {
                return this.optional(element) || /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/.test(value);
            }, "5-16位字母開頭,允許字母數字下劃線")

            jQuery.validator.addMethod("ppIdcheck", function(value, element) {
                return this.optional(element) || /^[1-9]([0-9]{14}|[0-9]{17})$/.test(value);
            }, "請輸入正確的身份證號碼(15-18位)")

            $("#form-sign-up").validate({
                rules: {
                    password: {required: true,usernamecheck: ""},
                    confirm_password: {required: true,minlength: 8,equalTo: "#password"},
                    username: {
                        required: true,
                        remote: ''
                    },
                    passportId:
                    {
                        required: true,
                        ppIdcheck: ""
                    }
                },
                messages: {
                        confirm_password: {
                        required: "請填寫一個密碼",
                        minLength: "長度必須8個字元",
                        equalTo: "請輸入與上面相同的密碼"
                    },
                    username: {
                        required: "請輸入使用者名稱",
                        remote: jQuery.format("{0} 已經有人用了")
                    },
                    checkbox11:
                    {
                        required: "請打勾"
                    }

                },
                // set this class to error-labels to indicate valid fields 
                success: function(label) {
                    // set   as text for IE 
                    label.html(" ").addClass("checked");
                },
                submitHandler: function(form) {
                    var formoption = {
                        dataType: "json",
                        url: '',
                        type: "post",
                        success: ProcessJson  // post-submit callback 
                    };
                    $(form).ajaxSubmit(formoption);

                } 
            });
        });
    script>

head>
<body>
    <form. method="post" id="form-sign-up">
    <h1>
        Demo表單h1>
    <table id="inputArea">
        <tr>
            <td>
                使用者名稱 (試試輸入 Petter):
            td>
            <td>
                <input type="text" name="username" id="username" />
            td>
        tr>
        <tr>
            <td>
                Email:
            td>
            <td>
                <input type="text" name="email" id="email" class="required email" />
            td>
        tr>
        <tr>
            <td>
                Url:
            td>
            <td>
                <input type="text" name="url" id="url" class="required url" />
            td>
        tr>
        <tr>
            <td>
                密碼:
            td>
            <td>
                <input type="password" name="password" id="password" />
            td>
        tr>
        <tr>
            <td>
                確認密碼:
            td>
            <td>
                <input type="password" name="confirm_password" id="confirm_password" />
            td>
        tr>
        <tr>
            <td>
                記住密碼
            td>
            <td>
                <input type="checkbox" name="checkbox11" id="checkbox" class="required" />
            td>
        tr>
        <tr>
            <td>
                <label for="passportId">
                    身份證號label>
                <em>*em>
            td>
            <td>
                <input type="text" name="passportId" id="passportId" class="required" />
            td>
        tr>
        <tr>
            <td colspan="2" align="center">
                <br />
                <input type="submit" id="btn1" value="提交" />
            td>
        tr>
    table>
    form>
body>
html>

View中使用是Jquery Validation,同樣是增加rule,用於客戶端驗證。具體可參考官方文件(後續有時間會放出中文版文件),以及之前這篇文章
JQuery+Asp.net MVC實現使用者名稱重名查詢


小結:在WEB頁面中,是一個資料進入的介面,對資料合法性,正確性非常重要。做好表單資料驗證工作可以防止那些攻擊資料,以及不合理資料。
通過使用客戶端和服務端雙重驗證,可以保證表單資料安全性。有的時候客戶端驗證並不是太安全的,可以設法繞開驗證提交表單。所以服務端驗證
也是需要的。但為了減輕伺服器壓力,儘量使用客戶端驗證。以上只是一個小小例子,歡迎討論。希望本文對您有幫助。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-553431/,如需轉載,請註明出處,否則將追究法律責任。

相關文章