Adi
Adi

Reputation: 525

Allowed Values of field in ASP.NET

Is there any data annotation for the allowed values in ASP.NET MVC Core? Since there is no enum in SQL server I am not able to migrate my class with enum field in it to the database. I want to give possible/allowed values to the field in the class. Is there any way to do this?

    public class Employee
    {
        [Key]
        public int ID { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Status { get; set; }

    }

I want to provide Active and Inactive as the only possible values to the Status field.

Upvotes: 5

Views: 8459

Answers (3)

Misha Zaslavsky
Misha Zaslavsky

Reputation: 9666

In .NET 8 Preview 2 you can use the AllowedValues attribute for that.

[Required]
[AllowedValues("Active", "Inactive")]
public string Status { get; set; }

For more info: https://devblogs.microsoft.com/dotnet/announcing-dotnet-8-preview-2/#allowedvaluesattribute-and-deniedvaluesattribute.

Upvotes: 5

Aris
Aris

Reputation: 5057

you can also do this using a regular expression as below:

[Required]
[RegularExpression("Active|Inactive", ErrorMessage = "Invalid Status")]
 public string Status { get; set; }

More details can by found here

Upvotes: 9

Matt U
Matt U

Reputation: 5118

As @ps2goat mentioned, you could use a check constraint on your database. However, for the model coming into the API you probably still want to provide validation there. Ideally you will do what you can, within reason, to prevent bad data from ever getting to the data layer. You don't mention whether you're using an n-tier architecture, or if your controller is directly referencing the data model. Either way, I believe this custom attribute can be used either at the API layer or on the entity model.

This is a good answer that explains how to create a custom validation attribute. It's an old answer, but it still applies to .Net Core. And here is an answer for a custom validation attribute in .Net Core. It basically looks like this:

public class EmployeeStatusAttribute : ValidationAttribute
{
    private string[] _allowedValues;

    public EmployeeStatusAttribute(string[] allowedValues)
    {
        _allowedValues = allowedValues;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var employee = value as Employee;
        if (_allowedValues.Contains(employee.Status))
        {
            return ValidationResult.Success;
        }
        return new ValidationResult(`{employee.Status} is not a valid status`);
    }
}

Then in your model:

public class Employee
{
    ...

    [EmployeeStatus("Active", "Inactive")]
    public string Status { get; set; }

    ...
}

Upvotes: 5

Related Questions