Search code examples
c#validationproperties.net-6.0data-annotations

Checking Property value: Data validation using Data Annotations - .NET


I am wanting to validate that a property value is set to a specific text. I came across [validation] (https://www.tutorialsteacher.com/mvc/implement-validation-in-asp.net-mvc) and saw how there are many options such as Required which is very helpful. But I do not see one to ensure that a property has a specific value. Is there a way I can do that using data annotations? Is regular expression for that?

i.e.

ClassName property must be set to "science". Is there a data annotation for property values? Is regular expression for that?

public class Student{
 [DataAnnotation("science")]
 public string ClassName{ get; set; }

}

I have searched over a few articles and still cannot find the solution to my problem. Would like to know if this is possible with data annotations?


Solution

  • You need to Use CustomValidationAttribute. Please refer below

    https://learn.microsoft.com/en-us/previous-versions/aspnet/cc668224(v=vs.100)

    https://www.codeproject.com/Tips/5257153/How-to-Create-Custom-Validation-Attribute-in-Cshar

    https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.customvalidationattribute?view=netframework-4.8

    Basically, these attributes will have Isvalid function. In you case you can put the validation as Property value == science