C # Web site uses features to implement data validation instances

Source: Internet
Author: User
Tags foreach reflection

The client's checksum is generally completed by JS, this article mainly introduces the use of features to complete the server-side data validation.

What is an attribute?

There are all kinds of goods in the supermarket, and the goods are labeled. The label may have information such as the name, price, category of the product. Before we buy something, we usually look at the label and get more information. Of course the main price, in case the money did not bring enough? :)
If the class as a commodity, then the feature is affixed to the product label. Features provide us with more information about the class. [Serializable] is the characteristic of a system commonly used in C #, through which we can know whether a class is allowed to be serialized.


Feature Verification Simple Demo

We've learned about features, so how do you validate data with attributes?
After the user registers, the user name and password are transferred to the server after the client's checksum. We first verify that the username is not empty, how to do it?
To get the idea right, we can do it in 3 steps:
1. Declare a custom attribute.
2, add custom attributes to the user class.
3, through the characteristics of data verification.

Declares a custom attribute.


[AttributeUsage (Attributetargets.property)] Class requiredattribute : attribute {     /// <summary>     ///  error message returned by validation failure     ///
 </summary>     public string errormessage     {
        get;
        set;
&NBSP;&NBSP;&NBSP;&NBSP}     /// <summary>     ///  input values
    /// </summary>     public object inputvalue     {        get;      
   set;
&NBSP;&NBSP;&NBSP;&NBSP}     /// <summary>     ///  validation rules     /// </summary>     /// <param naMe= "ErrorMessage" > Error message returned by validation failure </param>     public requiredattribute (string  errormessage)     {        this.
errormessage = errormessage;     }     /// <summary>     ///  Either the interface parameter is null or the empty string returns false     /// </summary>     /// < Returns></returns>     public  bool validate ()      {        return !string.
IsNullOrEmpty (Inputvalue.tostring ()); &NBSP;&NBSP;&NBSP;&NBSP}}


Custom attributes must inherit the attribute class, the [AttributeUsage (attributetargets.property)] attribute indicates that our custom attributes are only allowed to be added to the properties of the class. The Validate () method is the core logic of this feature, which is simple enough to verify that the value entered by the user is empty. Where does this value come from? Don't worry, we'll step in.


To add a custom attribute to a user class


public class User
{
[Required ("Please enter user name]]" public
string UserName {get; set;}
public string PassWord {get; set;}
}


Attributes can be added on classes, properties, methods, fields. This is added to the attribute because we only need to validate the value of the property, and when we customize the attribute, we declare that the attribute can only be added to the attribute. [Required ("Please enter user name")], we find that the attribute declaration is an instantiation of the attribute class, and the parameters that need to be passed in the parentheses are the arguments we declare the constructor. In fact, the custom feature is equivalent to the supermarket for labeling machines.
Verify the data through the attribute.

We can read the product by reading the label to know the product information, and then decide whether to buy. The same characteristics in the user class also need a person to read, we certainly can't read this feature, so who to find to do it? Yes, reflex.

Public string validate () {    //  reflection takes all properties of the current object      System.reflection.propertyinfo[] properties = this. GetType ().
GetProperties ();     foreach  (var pinfo in properties)     {  Attributes in        //  take properties         if
  (pinfo.isdefined (typeof (RequiredAttribute), false)         {             var customattributes =                  
Pinfo.getcustomattributes (typeof  (RequiredAttribute),  false)  as RequiredAttribute[];             //  validation of parameters based on characteristics              foreach  (var attribute in customattributes)              {               
 //  Initialize the features and verify them.                 var 
Validateval = pinfo.getvalue (This, null);                 attribute.
inputvalue = validateval;                 if  (! Attribute.
Validate ())                 {                      return  "Validation failed! Message: " + attribute."
errormessage;                 }              }         }         }     //  Verify Success     return  "Verify success!";}

The comments for the



Code are clear enough to explain the code.
Remember that we had a problem with the initialization of the value entered by the user? In fact, the value is reflected to take the value of attributes, to our characteristics.

Summary

Here we go. The entire feature validation process is really simple. Originally we verify that each data is written by itself to write a separate logic to verify. Now, we encapsulate the logic of validation into an attribute, which data needs to be added to this feature. Data validation, we just need to reflect the characteristics of the check on it. For example: When we buy something in a stall, we need to ask the stall owner for each item, how much does it cost? And supermarkets to each of the goods are labeled, price tag.

Related Article

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.