Robel Haile Robel Haile - 2 months ago 7
ASP.NET (C#) Question

On my C# properties in my class

I have this class


  • I want to validate the EmpType property so that can only take a value from the enum EmploymentType.

  • And then I want to validate EmplyomentNumber so that it starts with an "E" and includes 3 numbers

  • And then the salary property must be bigger or equal to 0.

    public class Employment
    {
    [Required, StringLength(50, MinimumLength = 3, ErrorMessage ="Name must be between 3 and 50 characters long.")]
    public string Name { get; set; }

    public EmploymentType EmpType { get; set; }
    public string EmplyomentNumber { get; set; }
    public decimal Salary { get; set; }
    }
    public enum EmploymentType
    {
    Full,
    Temporary,
    Internship
    }


Answer

If you want to validate EmployeeNumber, then use RegularExpressionAttribute. For example:

[RegularExpression("^[Ee]\d{3}$")]
public string EmployeeNumber{ get; set; }

As for the EmploymentType, the question here is how do you let users select this value? Is it via a dropdown list, radio button, etc.? If you are populating a dropdown list with the values in the enum, I think that all you need is to decorate your EmpType property with [Required] attribute.

For Salary property you can use [Range(0.1, 100000.0)]. The first value represents the minimum allowed value, and the latter is the maximum allowed value. Both values are required. You cannot specify just the minimum value without maximum, and vice versa.

For more information on available data annotations have a look at the MSDN Documentation.

Comments