Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataMember attributes for Data validation

I am looking to place attributes on my WCF data contract members to validate string length and possibly use regex for more granular parameter validation.

I can the [Range] attribute for numeric and DateTime values and was wondering if any of you have found any other WCF Data Member attributes I can use for data validation. I have found a bevvy of attributes for Silverlight but not for WCF.

like image 754
Jessica Avatar asked Oct 15 '12 14:10

Jessica


People also ask

What is DataMember attribute?

Data Member are the fields or properties of your Data Contract class. You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member. DataContractSerializer will serialize only those members, which are annotated by [DataMemeber] attribute.

How do I create a custom validation attribute?

To create a custom validation attributeUnder Add New Item, click Class. In the Name box, enter the name of the custom validation attribute class. You can use any name that is not already being used. For example, you can enter the name CustomAttribute.

What is Datacontract and DataMember?

A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.

What is Datacontract attribute?

[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.


3 Answers

Add System.ComponentModel.DataAnnotations reference to your project.

The reference provides some DataAnnotations which are:

RequiredAttribute, RangeAttribute, StringLengthAttribute, RegularExpressionAttribute

you can in your datacontract like below.

    [DataMember]
    [StringLength(100, MinimumLength= 10, ErrorMessage="String length should be between 10 and 100." )]
    [StringLength(50)]     // Another way... String max length 50
    public string FirstName { get; set; }

    [DataMember]
    [Range(2, 100)]
    public int Age { get; set; }

    [DataMember]
    [Required]
    [RegularExpression(@"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", ErrorMessage = "Invalid Mail id")]
    public string Email { get; set; }

Hope this helps.

like image 82
Prasad Kanaparthi Avatar answered Oct 21 '22 21:10

Prasad Kanaparthi


Manually Validating Values: You can manually apply the validation test by using the Validator class. You can call the ValidateProperty method on the set accessor of a property to check the value against the validation attributes for the property. You must also set both ValidatesOnExceptions and NotifyOnValidationError properties to true when data binding to receive validation exceptions from validation attributes.

var unsafeContact = Request["contactJSON"];
try
{
    var serializer = new DataContractJsonSerializer(typeof(Contact));
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(unsafeContact));
    Contact = serializer.ReadObject(stream) as Contact;
    stream.Close();
}
catch (Exception)
{
   // invalid contact
}

Contact class:

[DataContract]
public sealed class Contact
{
    /// <summary>
    /// Contact Full Name
    /// </summary>
    /// <example>John Doe</example>
    [DataMember(Name = "name", IsRequired = true)]
    [StringLength(100, MinimumLength = 1, ErrorMessage = @"Name length should be between 1 and 100.")]
    public string Name {
        get
        {
            return HttpUtility.HtmlEncode(_name);
        }
        internal set
        {
            Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Name" });
            _name = value;
        }
    }
    private string _name;

    // ...
}
like image 26
SavoryBytes Avatar answered Oct 21 '22 19:10

SavoryBytes


Try to look look for WCF Data Annotations. WCFDataAnnotations allows you to automatically validate WCF service operation arguments using System.ComponentModel.DataAnnotations attributes.

http://wcfdataannotations.codeplex.com/

like image 27
Milan Matějka Avatar answered Oct 21 '22 20:10

Milan Matějka