---
title: "How to create custom data annotations for custom validation on model property in .Net core?"  
description: "How to create custom data annotations for custom validation on model property in .Net core?"  
author: "Sandra Emily"  
published: 2023-10-20  
updated: 2023-10-22  
canonical: https://www.mindstick.com/forum/160248/how-to-create-custom-data-annotations-for-custom-validation-on-model-property-in-dot-net-core  
category: ".net core"  
tags: ["asp.net core", ".net core", "data annotations"]  
reading_time: 2 minutes  

---

# How to create custom data annotations for custom validation on model property in .Net core?

How to create custom [data annotations](https://www.mindstick.com/forum/160240/purpose-of-asp-dot-net-core-data-annotations) for [custom validation](https://www.mindstick.com/forum/1973/custom-validation-attribute) on [model](https://yourviews.mindstick.com/view/81334/america-is-reopening-after-corona-lockdown-but-on-swedish-model) [property](https://www.mindstick.com/blog/205/property-notification-in-c-sharp) in .Net core?

## Replies

### Reply by Aryan Kumar

In .NET Core, you can create [custom](https://www.mindstick.com/blog/12298/use-custom-writing-services-to-get-through-the-finals) [data](https://www.mindstick.com/articles/13050/salesforce-aiming-to-dominate-predictive-analytics-with-data-science) [annotations](https://www.mindstick.com/articles/12141/annotations-in-java-target-and-retention) for custom [validation](https://www.mindstick.com/articles/12234/validation-using-data-annotation-using-entity-framework) on model properties by creating your own custom validation attributes. This allows you to define custom validation rules and apply them to specific properties in your models. Here's how you can create custom data annotations for custom validation:

## Step 1: Create a Custom Validation Attribute Class:

You can create a custom validation attribute by inheriting from the **ValidationAttribute** class and overriding the **IsValid** method. Here's an example of a custom validation attribute for checking if a string contains a specific keyword:

```plaintext
using System;
using System.ComponentModel.DataAnnotations;

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class MustContainAttribute : ValidationAttribute
{
    private readonly string keyword;

    public MustContainAttribute(string keyword)
    {
        this.keyword = keyword;
    }

    public override bool IsValid(object value)
    {
        if (value is string strValue && !string.IsNullOrEmpty(strValue))
        {
            return strValue.Contains(keyword);
        }
        return true; // By default, the property is considered valid if it's not a string or empty.
    }
}
```

In this example, the **MustContainAttribute** checks if a string property contains a specified keyword.

## Step 2: Apply the Custom Attribute to a Model Property:

Now, you can apply your custom attribute to a property in your model. For example:

```plaintext
public class MyModel
{
    [MustContain("example")]
    public string Description { get; set; }
}
```

In this case, the **Description** property is decorated with the **MustContain** attribute, and it will be validated using the custom validation logic defined in the attribute.

## Step 3: Perform Validation in Your Code:

In your application code, you can use the **Validator.TryValidateObject** method to perform the validation on the model:

```plaintext
var myModel = new MyModel { Description = "This is an example description." };

var validationContext = new ValidationContext(myModel);
var validationResults = new List<ValidationResult>();

if (!Validator.TryValidateObject(myModel, validationContext, validationResults, validateAllProperties: true))
{
    foreach (var validationResult in validationResults)
    {
        Console.WriteLine(validationResult.ErrorMessage);
    }
}
```

The **TryValidateObject** method checks the **Description** property using the custom validation attribute and reports any validation errors.

Custom data annotations are powerful tools for creating custom validation rules for your model properties in .NET Core. They allow you to encapsulate validation logic and apply it to specific properties as needed.


---

Original Source: https://www.mindstick.com/forum/160248/how-to-create-custom-data-annotations-for-custom-validation-on-model-property-in-dot-net-core

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
