Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating properties in c#

let's suggest I got an interface and inherit class from it,

internal interface IPersonInfo
{
    String FirstName { get; set; }
    String LastName { get; set; }
}
internal interface IRecruitmentInfo
{
    DateTime RecruitmentDate { get; set; }
}

public abstract class Collaborator : IPersonInfo, IRecruitmentInfo
{
    public DateTime RecruitmentDate
    {
        get;
        set;
    }
    public String FirstName
    {
        get;
        set;
    }
    public String LastName
    {
        get;
        set;
    }
    public abstract Decimal Salary
    {
        get;
    }
}

then how do I validate strings in collaborator class? Is it possible to implement inside properties?

like image 841
lexeme Avatar asked Feb 09 '11 14:02

lexeme


People also ask

What is C validation?

The validation attributes specify behavior that you want to enforce on the model properties they are applied to. The Required attribute indicates that a property must have a value; in this sample, a movie has to have values for the Title , ReleaseDate , Genre , and Price properties in order to be valid.

How do you validate a model?

Models can be validated by comparing output to independent field or experimental data sets that align with the simulated scenario.

What is data validation in C#?

Data Validation is a list of rules to the data that can be entered in a cell. This can be applied by using IDataValidation interface.

What is validation context?

ValidationContext(Object) Initializes a new instance of the ValidationContext class using the specified object instance. ValidationContext(Object, IDictionary<Object,Object>) Initializes a new instance of the ValidationContext class using the specified object and an optional property bag.


1 Answers

Yes, but not using auto-properties. You will need to manually implement the properties with a backing field:

private string firstName;

public String FirstName
{
    get
    {
        return firstName;
    }
    set
    {
        // validate the input
        if (string.IsNullOrEmpty(value))
        {
            // throw exception, or do whatever
        }
        firstName = value;
    }
}
like image 181
Fredrik Mörk Avatar answered Sep 23 '22 15:09

Fredrik Mörk