文章出處

1.在Model類里面添加驗證,代碼如下:

 1  public class Movie
 2     {
 3         public int ID { get; set; }
 4         [StringLength(60,MinimumLength=3,ErrorMessage="主題的長度必須在3到60個字符")]
 5         public string Title { get; set; }
 6 
 7         [Display(Name="Release Date")]
 8         [DataType(DataType.Date)]
 9         [DisplayFormat(DataFormatString="{0:yyyy-MM-dd}",ApplyFormatInEditMode=true)]
10         public DateTime ReleaseDate { get; set; }
11         [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
12         [Required]
13         [StringLength(30)]
14         public string Genre { get; set; }
15         [Range(1,100)]
16         [DataType(DataType.Currency)]
17         public decimal Price { get; set; }
18 
19         [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
20         public string Rating { get; set; }
21 
22 
23     }
1 The StringLength attribute sets the maximum length of the string,  and it sets this limitation on the database, therefore the database schema will  change. Right click on the Movies table in Server  explorer and click Open Table Definition:
2 
3 這個StringLength屬性,設置了最大的字符串長度,限制了數據庫,所以數據庫結構會改變。我們先來看看數據庫結構沒改變之前的定義是咋樣的:

2.請看圖:

3.

 1 In the image above, you can see all the string fields are set to  NVARCHAR  (MAX).  We will use migrations to update the schema. Build the solution, and then open the Package Manager Console  window and enter the following commands:
 2 
 3 add-migration DataAnnotations
 4 update-database
 5 
 6 When this command finishes, Visual Studio opens the class file that defines  the new DbMIgration derived class with the name specified (DataAnnotations), and in the Up method you can see the code that updates the schema constraints:
 7 
 8 
 9 在上面的圖片中,你看到,所有的string類型的字段,都是NVARCHAR  (MAX),我們將會使用數據庫遷移技術,來更新表結構,打開程序包管理器控制臺,輸入下面的指令:
10 add-migration DataAnnotations
11 update-database
12 
13 當這個指令結束之后,VS打開生成的遷移文件,在Up方法中,你看到了添加的數據庫約束:

4.請看圖片:

5.下面,我們再來打開數據庫,看下數據表結構發生了什么變化:

6.

1 The validation attributes specify behavior that you want to enforce on the model  properties they are applied to. The Required  and MinimumLength attributes indicates that a property must have a  value; but nothing prevents a user from entering white space to satisfy this  validation.  The RegularExpression attribute is used to limit what characters can be input.  In the code above, Genre and Rating must use only  letters (white space, numbers and special characters are not allowed). The Range   attribute constrains a value to within a specified range. The StringLength  attribute lets you set the maximum length of a string property, and optionally  its minimum length. Value types (such as decimal, int, float, DateTime)  are inherently required  and don't need the Required attribute.
2 這個驗證屬性指定了你想要應用到Model中的屬性。Required和MinimumLength屬性,表明:必須要有一個值,但是不會阻止用戶輸入一個空格來滿足這個驗證。RegularExpression屬性,用來限制,什么字符可以被輸入,在上面的代碼中Genre和Rating字段必須只能是字母,(空格,數字還有其他的特殊字符都是不被允許的。),Range屬性約束了一個值必須在某個特定的范圍之內,StringLength屬性讓你可以設置,字符串的最大長度,值類型(例如;decilmal,int float,DateTime)都是內在需要的,然而對于Required來說,則并不需要。
3 
4 Code First ensures that the validation rules you specify on a model class are  enforced before the application saves changes in the database. For example, the  code below will throw a DbEntityValidationException exception when the SaveChanges method is  called, because several required Movie property values are missing:
5 
6 Code First 確保你指定在Model中的驗證,在數據庫數據保存前,能夠被驗證。例如下面的代碼,當SaveChanges調用的時候,將會拋出一個錯誤,因為有一些必須要的字段丟失了。
1 MovieDBContext db = new MovieDBContext();
2 Movie movie = new Movie();
3 movie.Title = "Gone with the Wind";
4 db.Movies.Add(movie);
5 db.SaveChanges();        // <= Will throw server side validation exception 

7.

1 Having validation rules automatically enforced by the .NET Framework helps  make your application more robust. It also ensures that you can't forget to  validate something and inadvertently let bad data into the database.
2 
3 數據驗證,通過 .NET Framework 自動的被執行,這可以使你的程序更健壯,同樣它會確保你,不會忘記去驗證一些,還有不是故意的要讓不好的數據更新到數據庫中。

8。下面我們開始驗證吧,運行項目;

1 Click the Create New link to add a new movie. Fill out the  form with some invalid values. As soon as jQuery client side  validation detects the error, it displays an error message.
2 
3 點擊這個新建的鏈接,去添加一個新的movie。輸入不合法的數據,然后就看到錯誤了。

1 Note to support jQuery validation for non-English locales  that use a comma (",") for a decimal point, you must include the NuGet  globalize as described previously in this tutorial.

9.

Notice how the form has automatically used a red border color to highlight  the text boxes that contain invalid data and has emitted an appropriate  validation error message next to each one. The  errors are enforced both client-side (using JavaScript and jQuery) and server-side (in case  a user has JavaScript disabled).
注意到:表單自動的使用了一個紅色的邊框來高亮顯示要驗證的文本框里面的錯誤數據。錯誤消息就顯示在旁邊。(PS:這里我節省時間,就隨便大概翻譯一下了,只是把大概的意思翻出來。)

A real benefit is that you didn't need to change a single line of code in the MoviesController class or in the Create.cshtml view in  order to enable this validation UI. The controller and views you created earlier  in this tutorial automatically picked up the validation rules that you specified  by  using validation attributes on the properties of the Movie model class.  Test validation using the Edit action method, and the same  validation is applied.
這個真正的好處是,你不必為了可以使用validation UI,而在控制器,或者在視圖頁面中去改變代碼,控制器和視圖頁面,捕獲了你在前面的Model類里面寫的驗證規則。測試驗證,我們使用編輯方法,這個驗證同樣適用于編輯的功能。

The form data is not sent to the  server until there are no client side validation errors. You can verify this by  putting a break point in the HTTP Post method, by using the fiddler tool, or the IE  F12 developer tools.
表單的數據,不會提交到服務器,除非沒有客戶端錯誤的驗證機制。你可以在瀏覽器中按F12,并在Post方法中,設置斷點來調試。

 10.驗證是怎樣出現在視圖和方法里面的呢:

You might wonder how the validation UI was generated without any updates to  the code in the controller or views. The next listing shows what the Create methods in the MovieController class look like.  They're unchanged from how you created them earlier in this tutorial.


你可能想到的是這個界面的驗證是怎樣在沒有修改控制器和視圖的情況下產生的呢。下面的代碼,是控制器的代碼,你之前創建的,沒有任何修改的
 1 public ActionResult Create()
 2 {
 3     return View();
 4 }
 5 // POST: /Movies/Create
 6 // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
 7 // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
 8 [HttpPost]
 9 [ValidateAntiForgeryToken]
10 public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Rating")] Movie movie)
11 {
12     if (ModelState.IsValid)
13     {
14         db.Movies.Add(movie);
15         db.SaveChanges();
16         return RedirectToAction("Index");
17     }
18     return View(movie);
19 }
1 The first (HTTP GET) Create action method displays the initial Create form. The second  ([HttpPost]) version handles  the form post. The second Create method (The HttpPost version) calls ModelState.IsValid to check whether the movie has any validation errors.  Calling this method evaluates any validation attributes that have been applied  to the object. If the object has validation errors, the Create  method re-displays the form. If there are no errors, the method saves the new  movie in the database. In our movie example, the form is not posted  to the server when there are validation errors detected on the client side;  the second Create method is never called. If you disable JavaScript  in your browser, client validation is disabled and the HTTP POST Create method calls ModelState.IsValid to check whether the movie has any validation errors.
2 
3 第一個Create方法(HTTP GET)展示初始的數據,第二個Create方法,處理表單的提交。第二個create方法,調用這個ModelState.IsValid 來檢查movie實體中是否有驗證不通過的數據。通過調用ModelState.IsValid可以來判斷是否有驗證屬性,作用在某個對象上面。如果這個對象出現驗證錯誤,這個Create方法,再次展示表單,如果沒有錯誤,就將數據保存到數據庫中。在我們的例子中,當客戶端驗證出現錯誤了,表單的數據是不會提交到服務器中的。這第二個Create方法是永遠不會被調用的。如果你禁止了瀏覽器的javascript,客戶端的驗證會失效,然后這個Post的方式的Create方法會調用ModelState.IsValid來檢查,是否Movie實體中有驗證不通過的。

11.

1 Below is the Create.cshtml view template that you scaffolded earlier in the tutorial. It's used by the action methods shown above both to display the initial form and to redisplay it in the event of an error.
2 
3 (PS:為了節約大家時間,就簡單翻譯一下了)
4 這句話的大概意思是:下面顯示的代碼,是用來顯示驗證失敗,而顯示的錯誤消息的:

12.

1 Notice how the code uses an Html.EditorFor helper to output the <input> element for each Movie property. Next to this  helper is a call to the Html.ValidationMessageFor helper method.  These two helper methods work with the model object that's passed by the  controller to the view (in this case, a Movie object). They  automatically look for validation attributes specified on the model and display  error messages as appropriate.
2 
3 What's really nice about this approach is that neither the controller nor the  Create view template knows anything about the actual validation rules being  enforced or about the specific error messages displayed. The validation rules  and the error strings are specified only in the Movie class. These  same validation rules are automatically applied to the Edit view and any other  views templates you might create that edit your model.
4 
5 If you want to change the validation logic later, you can do so in exactly  one place by adding validation attributes to the model (in this example, the movie class). You won't have to worry about different parts of the application  being inconsistent with how the rules are enforced — all validation logic will  be defined in one place and used everywhere. This keeps the code very clean, and  makes it easy to maintain and evolve. And it means that that you'll be fully  honoring the DRY principle.
6 
7 
8 這幾段話,本來我翻譯好了,結果電腦突然關機,沒保存。現在就不翻譯了,郁悶。。。

直接看代碼吧:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Data.Entity;
 6 using System.ComponentModel.DataAnnotations;
 7 
 8 namespace MvcMovie.Models
 9 {
10     public class Movie
11     {
12         public int ID { get; set; }
13         [StringLength(60,MinimumLength=3,ErrorMessage="主題的長度必須在3到60個字符")]
14         public string Title { get; set; }
15 
16         [Display(Name="Release Date")]
17         [DataType(DataType.Date)]
18         [DisplayFormat(DataFormatString="{0:yyyy-MM-dd}",ApplyFormatInEditMode=true)]
19         public DateTime ReleaseDate { get; set; }
20         [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
21         [Required]
22         [StringLength(30)]
23         public string Genre { get; set; }
24         [Range(1,100)]
25         [DataType(DataType.Currency)]
26         public decimal Price { get; set; }
27 
28         [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
29         public string Rating { get; set; }
30 
31 
32     }
33 
34     public class MovieDBContext : DbContext
35     {
36         public DbSet<Movie> Movies { get; set; }
37     }
38 }

13.

The  DataType attributes only provide hints for the view engine to format  the data (and supply attributes such as <a> for URL's and  <a  href="mailto:EmailAddress.com"> for email. You can use the RegularExpression attribute to validate the format of the data. The DataType attribute is used to specify a data type that is more specific than  the database intrinsic type, they are not validation  attributes. In this  case we only want to keep track of the date, not the date and time. The  DataType Enumeration provides for many data types, such as Date, Time,  PhoneNumber, Currency, EmailAddress and more. The DataType  attribute can also enable the application to automatically provide type-specific  features. For example, a mailto: link can be created for  DataType.EmailAddress,  and a date selector can be provided for  DataType.Date in browsers that support  HTML5. The DataType attributes emits HTML 5  data-  (pronounced data dash) attributes that HTML 5  browsers can understand. The DataType attributes do not provide any validation. 

DataType屬性只是提示了視圖引擎來格式化數據。你可以使用RegularExpression屬性來驗證格式化的數據,DataType不是驗證屬性,它和數據庫差不多,只是指定了數據類型而已,DataType枚舉類型,提供了很多數據類型,例如:Date,Time,PhoneNumber,Currency,EmailAddress等等,DataType屬性同樣能夠保證程序可以創建一些特殊的類型,比如a mailto: link 能夠被用來創建 DataType.EmailAddress。。。DataType不提供任何的驗證。



DataType.Date does not specify the format of the date  that is displayed. By default, the data field is displayed according to the default formats  based on the server's CultureInfo.

DataType.Date 不能指定顯示怎樣的格式化時間。它是默認根據服務器中的時間來的。


The DisplayFormat attribute is used to explicitly specify the  date format:

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }

14.

 1 The ApplyFormatInEditMode setting specifies that the specified formatting should also be applied when the value is displayed in a text box for editing. (You might not want that for some fields — for example, for currency values, you might not want the currency symbol in the text box for editing.)
 2 
 3 當處于文本編輯模式的時候,ApplyFormatInEditMode屬性就會被應用。(你可能不想讓這種情況應用于貨幣類型的字段,因為你不想讓貨幣類型的處于文本編輯模式下)
 4 
 5 
 6 You can use the DisplayFormat attribute by itself, but it's generally a good idea to use the DataType  attribute also. The DataType attribute conveys the semantics of the data as  opposed to how to render it on a screen, and provides the following benefits  that you don't get with DisplayFormat:
 7 
 8 這個時候,你可以用DisplayFormat,但是一個更好的主意是:使用DataType,這個屬性提供了幾個好處
 9 
10 The browser can enable HTML5 features (for example to show a  calendar control, the locale-appropriate currency symbol, email links, etc.).
11 瀏覽器支持HTML5特性
12 By default, the browser will render data using the correct format based on your locale.
13 瀏覽器默認會在你的本地電腦上面,正確顯示數據
14 The DataType attribute can enable MVC to choose the right field template to  render the data (the DisplayFormat if used by itself uses the string template). For more information, see Brad  Wilson's ASP.NET MVC 2 Templates. (Though written for MVC 2, this article still applies to the current version of ASP.NET  MVC.)
15 
16 DataType屬性能夠保證MVC選擇正確的字段,顯示數據(DisplayFormat它是使用字符串模板),了解更多請看。。。。
17 
18 If you use the DataType attribute with a date field, you have to specify the DisplayFormat attribute also in order to ensure that the field renders  correctly in Chrome browsers. For more information, see this StackOverflow thread. 
19 
20 如果你使用了DataType屬性,你不得不指定DisplayFormat屬性,來確保能夠在谷歌瀏覽器上面,正確顯示數據
21 
22 Note: jQuery validation does not work with the Range attribute and DateTime. For example, the following code will always display a client  side validation error, even when the date is in the specified range:
23 jQuery validation不支持Range,DateTime屬性,即使你指定了特定范圍,還是會報客戶端的驗證錯誤

看代碼:

[Range(typeof(DateTime), "1/1/1966", "1/1/2020")]

You will need to disable  jQuery date validation to use the  Range attribute with DateTime. It's generally not a good practice to compile hard dates in  your models, so using the Rangeattribute and DateTime is discouraged.

搞翻譯,真不是一件容易的事啊,還是得堅持!加油~~~to myself.

 


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()