[C#][ASP.NET MVC]Validation

  • 6893
  • 0
  • C#
  • 2010-02-23

[C#][ASP.NET MVC]Validation

網頁開發中驗證client端所提交的資料是否符合規定算很普遍的功能,自己紀錄一下。

 

簡單驗證(Server-Side)

Validation Methods     

 

 

 #region Validation Methods

        public bool ValidateNull(String type,String input)
        {
            String error = String.Empty;
            switch (type)
            {
                case "BookName":
                    error = "書籍名稱必填";
                    break;
                case "UserName":
                    error = "作者性名必填";
                    break;
            }
            if (String.IsNullOrEmpty(input))
            {
                ModelState.AddModelError(input, error);
            }
            return ModelState.IsValid;
        }

        public bool ValidateLength(String type, String input)
        {
            String error = String.Empty;
            switch (type)
            {             
                case "UserName":
                    error = "作者性名長度不能超過10個單字";
                    break;
            }
            if (input.Length>10)
            {
                ModelState.AddModelError(input, error);
            }
            return ModelState.IsValid;
        }

        #endregion

Create in Controller

 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            if (!ValidateNull("BookName", collection["BookName"]))
            {
                return View();
            }
            if (!ValidateNull("UserName", collection["UserName"]))
            {
                return View();
            }           
            try
            {
                // TODO: Add insert logic here               
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

結果

image image

image image

 

另一種方法,使用Data Annotation Validators。

先加入Microsoft.Web.Mvc.DataAnnotations.dll和System.ComponentModel.DataAnnotations.dll並引用


using System.ComponentModel.DataAnnotations; 

Register the DataAnnotations Model Binder in the Global.asax    

 

protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders.DefaultBinder = 
             new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();          
        }

 Add Models

namespace MVCcrud.Models
{
    public partial class BookRepository
    {
        [Required(ErrorMessage = "書籍名稱必填")]  
        public string BookName { get; set; }
        
        [Required(ErrorMessage = "作者性名必填")]
        [StringLength(10,ErrorMessage = "長度不能超過10個單字")]
        public string UserName { get; set; }
        public string Website { get; set; }
        [Required(ErrorMessage = "Email必填")]
        [RegularExpression("^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@
         ([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", ErrorMessage = "請輸入正確Email")]  
       
        public string Email { get; set; }       
    } 
}

 這時Create只要寫成這樣


 public ActionResult Create(BookRepository bookrepository)
        {
            //if (!ValidateNull("BookName", collection["BookName"]))
            //{
            //    return View();
            //}
            //else if (!ValidateNull("UserName", collection["UserName"]))
            //{
            //    return View();
            //}
            //else if (!ValidateLength("UserName", collection["UserName"]))
            //{
            //    return View();
            //}
            if (!ModelState.IsValid)
                return View();
        
            try
            {
                // TODO: Add insert logic here               
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

  結果

image image image

 當然還有其他方法大家可自行研究

 

參考

http://aspnet.codeplex.com/releases/view/24471

http://www.asp.net/(S(pdfrohu0ajmwt445fanvj2r3))/learn/mvc/tutorial-36-cs.aspx

http://www.asp.net/(S(pdfrohu0ajmwt445fanvj2r3))/learn/mvc/tutorial-39-cs.aspx

補充:ASP.NET MVC2看來不用這麼麻煩了。

Model Validation