2011-08-17 22 views
1

我啓用用戶使用我的asp.net應用程序將數據添加到SQL Server 2008數據庫。asp.net:如何做數據驗證?

什麼是插入數據和能夠驗證像空字段,整數與字符串的東西的最佳方式?

我目前使用formview來插入數據。我如何驗證用戶輸入?

+0

單挑,使用開箱驗證器時,您應該在服務器端進行驗證。對於整數與字符串,請使用RegularEspressionValidator。同樣看看反xss庫吧:) – IrishChieftain

+0

同意,我不會依賴asp:驗證器。請在xss腳本背後的代碼中做一個快速驗證,如 – griegs

回答

2

使用驗證jQuery插件進行前端驗證。

這是我用了很多。 http://bassistance.de/jquery-plugins/jquery-plugin-validation/

然後在c#中創建一個你的模型的部分類,並使用DataAnnotations做更深入的驗證。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.ComponentModel.DataAnnotations; 
using System.ComponentModel; 

    namespace DataRepository 
    { 
     [MetadataType(typeof(Company_validation))] 
     public partial class Company 
     { 
     } 


     public class Company_validation 
     { 
      [Required] 
      [DisplayName("Company name")] 
      public string Name { get; set; } 

      [Required] 
      [DisplayName("Address")] 
      public string AddressLine1 { get; set; } 
      public string AddressLine2 { get; set; } 

      [Required] 
      public string Suburb { get; set; } 

      [Required] 
      public int Postcode { get; set; } 

      [Required] 
      public string State { get; set; } 
     } 

    } 

所以從這裏你幾乎可以做任何你需要的驗證。

下面是我們在項目中使用過的RequiredFieldValidators的兩個示例。

RegularExpressions驗證器是你想檢查字符串與整數等或驗證電話號碼,郵政編碼或電子郵件;

<asp:RequiredFieldValidator ID="reqValTxtAppRef" runat="server" ErrorMessage="Please enter your application reference number or <a href='ChooseYourHealthCover.aspx'>click here</a> to begin a new application <br/>" 
ControlToValidate="txtAppRef" Display="Dynamic" ValidationGroup="vgRetrieveApp" 
SetFocusOnError="true" CssClass="error" Font-Bold="true" cau EnableClientScript="False" /> 

<asp:RegularExpressionValidator ID="regexpValTxtAppRef" runat="server" ControlToValidate="txtAppRef" ErrorMessage="This is not a valid application reference number. Please enter it again or <a href='ChooseYourHealthCover.aspx'>click here</a> to begin a new application <br>" ValidationExpression="(HQ|HA|hq|ha)\d{8}" ValidationGroup="vgRetrieveApp" Display="Dynamic" CssClass="error" Font-Bold="true" EnableClientScript="False" /> 
+0

有沒有簡單的asp.net解決方案? –

+0

requiredfieldvalidator怎麼樣? –

+0

asp:controls上的RequiredFieldValidator工作正常,但jQuery插件爲您提供了更多的控制權。至於asp.net解決方案,你使用c#代碼進行後端驗證,所以... – griegs

1

我得到舒服asp.net驗證器第一......在那之後,有一些非常好的那些使用jQuery等

這裏是一個偉大的地方得到一個概述,以及看到他們在行動。它有一個沙箱區域,您也可以在那裏進行測試。 http://www.w3schools.com/aspnet/aspnet_refvalidationcontrols.asp

+0

發送給你一個msg的討論 –

+0

你能幫助這個嗎? http://stackoverflow.com/questions/7124212/display-content-depending-on-which-user-in-asp-net –