Data Annotations in C#
Data validation ensures that only correct and expected data reaches our databases, as user input can be unpredictable. We can use various validation methods, including Fluent Validation and Data Annotations to achieve this.
In this article, we’ll explore how to implement data annotations effectively in a web application.
Applying Validation Using Data Annotations
Data annotations allow us to apply validation by adding attributes to model properties. The System.ComponentModel.DataAnnotations namespace provides these attributes by default in .NET, with no additional setup needed.
Common Validation Attributes
Common validation attributes include:
-
[Required]
-
[StringLength]
-
[Range]
-
[RegularExpression]
-
[EmailAddress]
-
[Compare]
-
[MinLength]
-
[MaxLength]
-
[AllowedValues]
We’ll explore each of these with code examples.
Using Validation Attributes in C#
[Required]
Ensures that a property is not null or empty :
using System.ComponentModel.DataAnnotations;
namespace DataAnnotations.Models;
public sealed class User
{
[Required]
public string Name { get; set; }
... Other properties ...
}
This field is now required, and if a value is not provided, an error message will be displayed like this.
To customize the default error message, we can add the ErrorMessage attribute, like this :
public sealed class User
{
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
... Other properties ...
}
[StringLength]
Specifies the minimum and maximum length of a string property :
public sealed class User
{
[StringLength(maximumLength:100,
MinimumLength=6,
ErrorMessage="Password must be between 6 and 100 characters")]
public string Password { get; set; }
... Other properties ...
}
[Range]
Defines a numeric range for a property :
public sealed class User
{
[Range(18, 65, ErrorMessage = "Age must be between 18 and 65")]
public int Age { get; set; }
... Other properties ...
}
[RegularExpression]
Validates a property against a regular expression pattern :
public sealed class User
{
[RegularExpression(@"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$",
ErrorMessage = "Invalid email format.")]
public string Email { get; set; }
... Other properties ...
}
[EmailAddress]
Validate a property whether it is a valid email or not:
public sealed class User
{
[EmailAddress(ErrorMessage ="Email address is not valid")]
public string Email { get; set; }
... Other properties ...
}
[Compare]
It compares the value of one property with another and makes sure both are the same:
public sealed class User
{
[Required]
[Compare("Password",
ErrorMessage = "Password and ConfirmPassword should be same")]
public string ConfirmPassword { get; set; }
[Required]
public string Password { get; set; }
}
[MinLength] and [MaxLength]
Another way to specify the minimum and maximum length of a string or array type property :
public sealed class User
{
[Required]
[MinLength(4)]
[MaxLength(20)]
public string Name { get; set; }
... Other properties ...
}
[AllowedValues]
Gets the list of values allowed by this attribute :
public sealed class User
{
[AllowedValues(UserTypes.Admin)]
public UserTypes UserType { get; set; }
... Other properties ...
}
public enum UserTypes
{
Admin,
Customer
}
How validation is triggering
If you’re wondering how this validation is triggered, you’ll need to add asp-validation-for it to your HTML(View in my case for MVC)
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
Additional Purposes of Data Annotations
Data annotations can also serve additional purposes beyond validation, such as:
[Display]
Specifies how data, including name, description, and order, is displayed in the UI.
[DisplayFormat]
Specifies the format for displaying data, such as date and currency formats.
[DataType]
Provides additional type information, such as DataType.Date, DataType.Time, DataType.Currency, etc.
[Key]
Specifies that a property is the primary key of an entity.
[ForeignKey]
Specifies a foreign key relationship between entities.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place