【譯】MVC3 20個秘方-(3)驗證用戶的輸入
場景
你要確保你的表單捕獲的數據包含你預期的數據,這些數據是基于你的數據庫或模型設計。
解決方案
.NET 4.0 包含了一個新的數據注解命名空間,提供了一些有用的元數據屬性類。這些類已經被應用到MVC3。
對于驗證表單輸入,下面的屬性類可以用來提供各種各樣
驗證選項:RequiredAttribute,RegularExpressionAttribute,RangeAttribute和DataTypeAttribute。當需要自定義的驗證的時候,MVC的3還支持改進ValidationAttribute類,允許開發人員定義的驗證。
討論
接下來的例子是要去擴展“code-first book“model,這個model是在前一“秘方”中創建的。
這個model將按照以下條件被更新:
1. 書名是必須的
2. ISBN是合法的
3. 書的摘要是必須的
4. 作者是必須的
5. 合法的價格(美元)
6. 合法的出版日期
以上6個驗證中的5個可以由MVC 3 的內置方法完成。然而,第5個驗證需要用一種不同的格式化-它需要一個自定義驗證方法。
public class Book
{
public int ID { get; set; }
[Required]
public string Title { get; set; }
[Required]
[IsbnValidation]
public string Isbn { get; set; }
[Required]
public string Summary { get; set; }
[Required]
public string Author { get; set; }
public string Thumbnail { get; set; }
[Range(1, 100)]
public double Price { get; set; }
[DataType(DataType.Date)]
[Required]
public DateTime Published { get; set; }
}
public class BookDBContext : DbContext
{
public DbSet<Book> Books { get; set; }
}
在上邊的例子,[Required]數據注解被附加在每個字段上,表明這個字段是必須由用戶提供。在ISBN number上 [IsbnValidation]特性也被添加了,這是通知MVC 3 IsbnValidation 必須調用IsValid操作,這個操作即將被創建.為了驗證價格,[Range] 注解被應用。對于價格的驗證,我們也可以用正則表達式特性 [RegularExpression] 來完成。
如下:
[RegularExpression (@"(\b[\d\.]*)")]
public double Price { get; set; }
最后,對于published date(出版日期)的驗證,DataType特性告訴MVC這個字段的類型是一個日期類型。
一個合法ISBN的定義是:10-13個字符。為何合理的組織代碼,自定義驗證類將被放在一個單獨的文件夾里。
右鍵點擊項目:添加->新建文件夾。我們為這個文件夾命名為:Validations.在該文件夾點擊右鍵。添加類:IsbnValidationAttribute.cs
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
namespace MvcApplication.Validations
{
[AttributeUsage(AttributeTargets.Field |
AttributeTargets.Property, AllowMultiple = false,
Inherited = true)]
public class IsbnValidationAttribute :
System.ComponentModel.DataAnnotations.ValidationAttribute
{
/**
* This class is courtesy:
* http://www.java2s.com/Open-Source/CSharp/
* Inversion-of-Control-Dependency-Injection/Spring.net/
* Spring/Validation/Validators/ISBNValidator.cs.htm
*
* This class is used for demonstration purposes
* of performing an ISBN validation. Should you
* wish to use this in your project, please
* consult the license agreement here:
* http://www.apache.org/licenses/LICENSE-2.0
**/
private static readonly String SEP = "(?:\\-|\\s)";
private static readonly String GROUP = "(\\d{1,5})";
private static readonly String PUBLISHER = "(\\d{1,7})";
private static readonly String TITLE = "(\\d{1,6})";
static readonly String ISBN10_PATTERN =
"^(?:(\\d{9}[0-9X])|(?:" + GROUP + SEP + PUBLISHER +
SEP + TITLE + SEP + "([0-9X])))$";
static readonly String ISBN13_PATTERN =
"^(978|979)(?:(\\d{10})|(?:" + SEP + GROUP + SEP +
PUBLISHER + SEP + TITLE + SEP + "([0-9])))$";
public IsbnValidationAttribute() :
base("Invalid ISBN number")
{
}
public override bool IsValid(object value)
{
// Convert to string and fix up the ISBN
string isbn = value.ToString();
string code = (isbn == null)
? null :
isbn.Trim().Replace("-", "").Replace("", "");
// check the length
if ((code == null) || (code.Length < 10
|| code.Length > 13))
{
return false;
}
// validate/reformat using regular expression
Match match;
String pattern;
if (code.Length == 10)
{
pattern = ISBN10_PATTERN;
}
else
{
pattern = ISBN13_PATTERN;
}
match = Regex.Match(code, pattern);
return match.Success && match.Index == 0 &&
match.Length == code.Length;
}
}
}
創建完這個類記得在 book.cs添加命名空間引用:using MvcApplication.Validations;
上邊的例子包含了一個標準的ISBN驗證。這個驗證是來自CSharp Open Source example。如果ISBN符合2個正則表達式中的一個。驗證函數將返回true。否則返回false。需要用戶重新輸入
如果你在你的瀏覽器里轉到圖書創建頁面。當你點擊提交按鈕。驗證就被會觸發。
另請參閱:
譯者注:
關于用戶驗證,可以有更多方法,支持客戶端/服務器端驗證。
由于是翻譯,我會盡量和原著保持一致,關于其他的驗證方法會在后續的其他系列寫出。

浙公網安備 33010602011771號