淺談在ASP.NET中資料有效性校正的方法

來源:互聯網
上載者:User
asp.net|資料 作為一名程式員,一定要對自己編寫的程式的健壯性負責,因此資料的校正無論在商業邏輯還是系統實現都是必不可少的部分。

我這裡總結了一種自認為比較不錯的asp.net(C#)的資料校正方法,如大家探討。

主要用Regex的IsMatch方法,在BusinessRule層進行校正資料的有效性,並將校正的方法作為BusinessRule層基類的一部分。

在WebUI層現實提示資訊。

using System;
using System.Data;
using System.Text.RegularExpressions;
namespace Education.BusinessRules
{
/// <summary>
/// 商業規則層的基類
/// </summary>
public class BizObject
{
public const String REGEXP_IS_VALID_EMAIL = @"^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$"; //電子郵件校正常量
public const String REGEXP_IS_VALID_URL = @"^http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"; //網址校正常量
public const String REGEXP_IS_VALID_ZIP = @"\d{6}"; //郵編校正常量
public const String REGEXP_IS_VALID_SSN = @"\d{18}|\d{15}"; //身份證校正常量
public const String REGEXP_IS_VALID_INT = @"^\d{1,}$"; //整數校正常量
public const String REGEXP_IS_VALID_DEMICAL = @"^-?(0|\d+)(\.\d+)?$"; //數值校正常量 "
//日期校正常量
public const String REGEXP_IS_VALID_DATE = @"^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(\/|-|\.)(?:0?2\1(?:29))$)|(?:(?:1[6-9]|[2-9]\d)?\d{2})(\/|-|\.)(?:(?:(?:0?[13578]|1[02])\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\2(?:0?[1-9]|1\d|2[0-8]))$";

public BizObject(){}

#region 校正欄位是否為空白 或 欄位長度超長 方法

public string GetFieldTooLongError(string ErrorField,int maxlen)
{
return ErrorField + "資訊超長,請刪減至" + maxlen.ToString() + "個字元!" ;
}

public string GetFieldNullError(string ErrorField)
{
return ErrorField + "是必填項,不允許為空白!" ;
}

public bool IsValidField(DataRow Row, String fieldName, int maxLen,string ErrorField ,bool AllowNull)
{
int i = (short)(Row[fieldName].ToString().Trim().Length);

if ( i < 1 && (!AllowNull))
{
Row.SetColumnError(fieldName, GetFieldNullError(ErrorField));
return false;
}
else if (i > maxLen )
{
Row.SetColumnError(fieldName, GetFieldTooLongError(ErrorField,maxLen));
return false;
}
return true;
}
#endregion

#region 校正 電子郵件 類型欄位格式 方法

public string GetEmailFieldError(string ErrorField)
{
return ErrorField + "格式不正確(a@b.c)!" ;
}
public bool IsValidEmail(DataRow Row, String fieldName,int maxLen ,string ErrorField,bool AllowNull)
{
int i = (short)(Row[fieldName].ToString().Trim().Length);

bool isValid = IsValidField(Row,fieldName, maxLen , ErrorField , AllowNull);

if ( isValid )
{
isValid = (new Regex(REGEXP_IS_VALID_EMAIL)).IsMatch(Row[fieldName].ToString());

if ( (!isValid) && (i > 0))
{
Row.SetColumnError(fieldName, GetEmailFieldError(ErrorField));
return false;
}
}
return true;
}
#endregion

#region 校正 郵編 類型欄位格式 方法

public string GetZipFieldError(string ErrorField)
{
return ErrorField + "格式不正確(157032)!" ;
}
public bool IsValidZip(DataRow Row, String fieldName,int maxLen ,string ErrorField,bool AllowNull)
{
int i = (short)(Row[fieldName].ToString().Trim().Length);

bool isValid = IsValidField(Row,fieldName, maxLen , ErrorField , AllowNull);

if ( isValid )
{
isValid = (new Regex(REGEXP_IS_VALID_ZIP)).IsMatch(Row[fieldName].ToString());

if ( (!isValid) && (i > 0))
{
Row.SetColumnError(fieldName, GetZipFieldError(ErrorField));
return false;
}
}
return true;
}
#endregion

#region 校正 身份證 類型欄位格式 方法

public string GetSSNFieldError(string ErrorField)
{
return ErrorField + "格式不正確(長度為15或18位)!" ;
}
public bool IsValidSSN(DataRow Row, String fieldName,int maxLen ,string ErrorField,bool AllowNull)
{
int i = (short)(Row[fieldName].ToString().Trim().Length);

bool isValid = IsValidField(Row,fieldName, maxLen , ErrorField , AllowNull);

if ( isValid )
{
isValid = (new Regex(REGEXP_IS_VALID_SSN)).IsMatch(Row[fieldName].ToString());

if ( (!isValid) && (i > 0))
{
Row.SetColumnError(fieldName, GetSSNFieldError(ErrorField));
return false;
}
}
return true;
}
#endregion

#region 校正 網址 類型欄位格式 方法

public string GetUrlFieldError(string ErrorField)
{
return ErrorField + "格式不正確(http://www.abc.com)!" ;
}
public bool IsValidUrl(DataRow Row, String fieldName,int maxLen ,string ErrorField,bool AllowNull)
{
int i = (short)(Row[fieldName].ToString().Trim().Length);

bool isValid = IsValidField(Row,fieldName, maxLen , ErrorField , AllowNull);

if ( isValid )
{
isValid = (new Regex(REGEXP_IS_VALID_URL)).IsMatch(Row[fieldName].ToString());

if ( (!isValid) && (i > 0))
{
Row.SetColumnError(fieldName, GetUrlFieldError(ErrorField));
return false;
}
}
return true;
}
#endregion

#region 校正 日期 類型欄位格式 方法

public string GetDateFieldError(string ErrorField)
{
return ErrorField + "日期格式不正確!" ;
}
public bool IsValidDate(DataRow Row, String fieldName,int maxLen ,string ErrorField,bool AllowNull)
{
int i = (short)(Row[fieldName].ToString().Trim().Length);

bool isValid = IsValidField(Row,fieldName, maxLen , ErrorField , AllowNull);

if ( isValid )
{
isValid = (new Regex(REGEXP_IS_VALID_DATE)).IsMatch(Row[fieldName].ToString());

if ( (!isValid) && (i > 0))
{
Row.SetColumnError(fieldName, GetDateFieldError(ErrorField));
return false;
}
}
return true;
}
#endregion

#region 校正 數值 類型欄位格式 方法
//這也是個判斷數值的辦法
private bool IsNumeric(string Value)
{
try
{
int i = int.Parse(Value);
return true;
}
catch
{ return false; }
}

public string GetFieldNumberError(string ErrorField)
{
return ErrorField + "必須是數字(例如:90)!" ;
}

public bool IsValidNumber(DataRow Row, String fieldName,string ErrorField,bool AllowNull)
{
int i = (short)(Row[fieldName].ToString().Trim().Length);

bool isValid = (new Regex(REGEXP_IS_VALID_DEMICAL)).IsMatch(Row[fieldName].ToString());

if ( i < 1 && (!AllowNull))
{
Row.SetColumnError(fieldName, GetFieldNullError(ErrorField));
return false;
}
else if ( (!isValid) && (i > 0))
{
Row.SetColumnError(fieldName, GetFieldNumberError(ErrorField));
return false;
}
return true;
}
#endregion

}
}



//在繼承了基類的BusinessRule中使用校正的方法
/// <summary>
/// 使用上面的方法對資料進行有效性校正
/// </summary>
/// <param name="Row">資料行</param>
/// <returns>通過--true 不通過--false</returns>
public bool Validate(DataRow Row)
{
bool isValid;
Row.ClearErrors();
isValid = IsValidField(Row, "name", 20 ,"姓名",false);
isValid &= IsValidZip(Row, "zip", 6,"郵編",true);
isValid &= IsValidNumber(Row, "age","年齡",false);
isValid &= IsValidEmail(Row,"email",50,"電子郵件" ,true);
return isValid;
}



//在WebUI中顯示錯誤提示資訊
/// <summary>
/// 顯示提交資料返回的錯誤資訊
/// </summary>
private void DisplayErrors()
{
String fieldErrors="";
String tmpfieldErrors="";

DataRow Row = ds.Tables[0].Rows[0];

foreach (DataColumn Column in ds.Tables[0].Columns)
{
tmpfieldErrors = Row.GetColumnError(Column.ColumnName.ToString());
if (tmpfieldErrors!="")
{
fieldErrors += "<li>" + tmpfieldErrors + "<br>";
}
}
//顯示錯誤資訊
this.lblError.Text = fieldErrors;
}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.