20 tips for ASP. net mvc 3 Development (3) [20 recipes for programming MVC 3]: Verify user input

Source: Internet
Author: User

Topics

Add verification during design to ensure that the input content in the form matches the type of the database and model design.

Solution

The new namespace dataannotations in. Net 4.0 MVC 3 provides many useful metadata attributes. To verify the input of a form, the following attribute classes provide multiple verification methods: requireattribute, regularexpressionattribute, and datatypeattribute. When you need to define the content that must be entered, MVC 3 allows developers to define verification through the improved validationattribute class.

 

Discussion

In the previousCodeIn the secret of priority, we create the book model and we will update it as follows:

    1. Enter the name of the book;
    2. Enter and verify ISBD;
    3. Enter the book abstract;
    4. Enter the author of the book;
    5. Enter and verify the book price (USD );
    6. Enter and verify the publication time.

Five of the six input items can be verified through the built-in verification method of MVC 3. However, the ISBN format requires different authentication methods-custom verification methods:

 Using System;
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Data. entity;
Using System. componentmodel. dataannotations;
Using Mvcapplication4.validations;

Namespace Mvcapplication4.models
{
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 [Require] attribute identifies fields that must be entered by the user. The isvalid attribute must be added to the isbnvalidationattribute class to notify MVC 3 of the call during the operation. To verify the price, add the [range] class to the price field and set the [regularexpression] attribute as follows:

[Range (1,100)]
[Regularexpression (@"(\ B [\ D \.] *)")]
Public DoublePrice {Get;Set;}

 

Finally, the published member type is time by defining the datatype attribute. Currently, the isbnvalidation class does not display any errors during verification. Next we will implement it.

The valid length of ISBN is 10 to 13 characters. To better organize the code, place the custom verification code and other verification code files in a separate folder and save them. Right-click the project, select "add"> "create folder", and rename the folder as "validations ". Select "add"-> "class" and name it "isbnvalidationattribute. cs". This class inherits the validationattribute class and overrides the isvalid method to verify the input ISBN content:

 Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Text. regularexpressions;

Namespace Mvcapplication4.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;
}
}
}

The above example is a C # Open Source example that contains an ISBN standard verification.Program. The isvalid method matches two verification rules. If it passes the verification rule, true is returned. Otherwise, false is returned and the user is requested to enter it again.

 

When you access and submit the book creation page, the above error message appears until all input items have entered correct data. Whether the modelstate. isvalid attribute is true must be determined if this check is successful.

 

References

Dataannotations namespace original book Address Book source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.