This is a mirror of official site: http://jasper-net.blogspot.com/

Using Data Annotations in the .NET Framework

| Sunday, February 26, 2012
Starting with .NET 4 or MVC3, a developer could use a data annotation on a property to force data validation. This is extremely powerful especially for MVC developers. The same data annotations can also be used when building custom modules for Orchard CMS.

The annotations built into the framework include the following:

    Required – Allows you to mark a property as being required.
    StringLength – Allows a maximum string length to be specified for a property.
    Range – Validates the value of the specified property is between a range of values.
    RegularExpression – Allows you to specify a regular expression to validate the content against. A comprehensive list of regular expressions can be found at http://regexlib.com/.

In addition to these above, custom annotations can be built by inheriting from the base class ValidationAttribute.

An example of a custom data annotation is shown below. This sample asks for a start and an end date to be specified as strings. The assumption is that these strings will be in a correct date format. A property value will be specified as a string. The property value must be between the two dates specified.

public class DateRange : System.ComponentModel.DataAnnotations.ValidationAttribute
{
    public string StartDate { get; set; }
    public string EndDate { get; set; }
 
    public DateRange() {
        this.StartDate = new DateTime(1900, 1, 1).ToString();
        this.EndDate = new DateTime(2099, 1, 1).ToString();
    }
 
    public override bool IsValid(object value) {
        var valueToString = value as string;
            
        if (!string.IsNullOrEmpty(valueToString)) {
            DateTime dateTimeResult;
                
            if (DateTime.TryParse(valueToString, out dateTimeResult)) {
                return ((dateTimeResult >= DateTime.Parse(this.StartDate)) && (dateTimeResult <= DateTime.Parse(this.EndDate)));
            }
 
            return false;
        }
        return true;
    }
}


Read more: Jason N. Gaylord
QR: Inline image 1

Posted via email from Jasper-net

0 comments: