views:

602

answers:

1

When I am not using data controls like the DataForm and DataGrid is there any use for the attributes like [Required], [StringLength] on my entities? Can these be used for validation outside of the above mentioned data controls?

If so, could you point me to some examples or documentation. I would like to prevent users from pressing the OK button if there are any validation errors and would like to avoid the throwing of exceptions from the setters(possible?).

A: 

Yes, those can be used for validation without using UI controls. Brad Abrams has a blog post with details on using those attributes for data forms, but seems like you should be able to separate the UI portion of his post from the core validation logic.

From the post, here's a sample property with validation logic added manually.

[DataMember()]
[Key()]
[ReadOnly(true)]
public int EmployeeID
{
    get
    {
        return this._employeeID;
    }
    set
    {
        if ((this._employeeID != value))
        {
            ValidationContext context = new ValidationContext(
                this, null, null);
            context.MemberName = "EmployeeID";
            Validator.ValidateProperty(value, context);
            this._employeeID = value;
            this.OnPropertyChanged("EmployeeID");
        }
    }
}
Brad Tutterow
This works well if the user has modified some exisitng value or entered a value.
DaveB