[英]C# - validation attributes
我使用C#MVC,我有一個列表:
public List<int?> SomeList { get; set; }
當用戶嘗試輸入字母而不是數字時,它會顯示驗證錯誤,因為列表的類型是INT。
我想為列表的項目添加更多的驗證,例如“ range”(不僅如此)(它們都將具有相同的屬性)。
我可以那樣做嗎? 怎么樣?
您可能想研究一下rangeattribute的來源,並創建自己的屬性( http://msdn.microsoft.com/en-us/library/cc668224.aspx ),該屬性將驗證具有范圍的通用列表。
有呀。
您始終可以自己實施驗證,尤其是要在各種條件下實施任意驗證時
bool validate(int value){
if ((value < min) || (value > max))
return false;
}
您必須創建自己的繼承自List<T>
,然后可以通過聲明一個新方法來“隱藏” Add方法:
class TestList : List<int>
{
public int MinValue { get; set; }
public int MaxValue { get; set; }
public TestList(int minValue, int maxValue)
{
this.MinValue = minValue;
this.MaxValue = maxValue;
}
public new void Add(int item)
{
if (item < MinValue || item > MaxValue)
throw new ArgumentException("Value is outside the acceptable range");
base.Add(item);
}
}
編輯:忘記拋出構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.