Scenario
Make sure that the data captured in your form contains the data you expected. The data is designed based on your database or model.
Solution
. Net 4.0 contains a new data annotation namespace and provides some useful metadata attribute classes. These classes have been applied to mvc3.
For verification form input, the following attribute classes can be used to provide a variety
Verification options: requiredattriattribute, regularexpressionattribute, rangeattribute, and datatypeattribute. When custom verification is required, MVC 3 also supports improving the validationattribute class, allowing developers to define verification.
Discussion
The following example is to extend the "Code-First Book" model, which was created in the previous "secret recipe.
This model will be updated according to the following conditions:
1. The title is required
2. ISBN is legal
3. The abstract of the book is required.
4. The author is required.
5. Valid price (USD)
6. Legal Publication date
5 of the above 6 verifications can be completed by the built-in MVC 3 method. However, the 5th verification requires a different format-it requires a custom verification method.
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 ;}
}
In the preceding example, the [required] data annotation is appended to each field, indicating that this field must be provided by the user. The [isbnvalidation] feature is also added on ISBN number, which notifies MVC 3 that isbnvalidation must call the isvalid operation, which is about to be created. To verify the price, the [range] annotation is applied. For price verification, we can also use the regular expression feature [regularexpression.
As follows:
[Regularexpression (@ "(\ B [\ D \.] *)")]
Public double price {Get; set ;}
Finally, for Published Date verification, the datatype feature tells MVC that the field type is a date type.
A valid ISBN is defined as 10-13 characters. Rational organizationCode, The custom authentication class will be placed in a separate folder.
Right-click Project: Add-> Create folder. We named this folder validations. Right-click the folder. Add class: isbnvalidationattribute. CS
The Code is as follows:
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 parameter Ming An ISBN validation. shoshould 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;
}
}
}
After creating this class, remember to add the namespace reference in book. CS: Using mvcapplication. validations;
The preceding example contains a standard ISBN verification. This verification is from CSHARP open source example. If ISBN matches one of the two regular expressions. The verification function returns true. Otherwise, false is returned. The user needs to re-enter
If you go to the book creation page in your browser. Click Submit. Verification is triggered.
For more information, see:
Dataannotations namespace
Translator's note:
There are more methods for user authentication, supporting Client/Server verification.
As it is a translation, I will try my best to be consistent with the original article. Other verification methods will be written in other series in the future.