Real-Time Examples of Data Annotations in ASP.NET Core MVC

Real-Time Examples of Data Annotations in ASP.NET Core MVC

In this article, I will discuss Multiple Real-Time Examples of Data Annotations in ASP.NET Core MVC Applications. Please read our previous article discussing BindNever and BindRequired Attribute in ASP.NET Core MVC.

Real-Time Examples of Data Annotations in ASP.NET Core MVC

Data annotations play a crucial role in ASP.NET Core MVC applications, providing a way to enforce validation rules and define configuration settings for models. Here are some real-time, practical examples of how data annotations might be used:

User Registration Form:

When creating a user registration form, you want to ensure data integrity and provide feedback to the user.

public class RegisterViewModel
{
    [Required(ErrorMessage = "Email is required.")]
    [EmailAddress(ErrorMessage = "Enter a valid email address.")]
    [Display(Name = "Email Address")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at most {1} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm Password")]
    [Compare("Password", ErrorMessage = "Passwords do not match.")]
    public string ConfirmPassword { get; set; }
}
Product Listing in an E-Commerce Application:

In an e-commerce application, you’d want to have constraints and proper display settings for your product model when listing products.

public class Product
{
    [Key]
    public int ProductId { get; set; }

    [Required]
    [StringLength(255)]
    [Display(Name = "Product Name")]
    public string Name { get; set; }

    [Required]
    [Range(0.01, 99999.99, ErrorMessage = "Price must be between 0.01 and 99999.99.")]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    [StringLength(2000)]
    [Display(Name = "Product Description")]
    public string Description { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime ReleaseDate { get; set; }
}
Employee Management System:

For an application that manages employees, you’d likely want to enforce validation and structure to your data.

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

    [Required]
    [StringLength(100)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(100)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [Range(18, 65, ErrorMessage = "Age should be between 18 and 65.")]
    public int Age { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Phone]
    public string PhoneNumber { get; set; }

    [Display(Name = "Date of Joining")]
    [DataType(DataType.Date)]
    public DateTime JoinDate { get; set; }
}
Feedback Form:

You’d want to gather accurate and relevant information for a feedback or contact form on a website.

public class FeedbackViewModel
{
    [Required]
    [StringLength(100)]
    [Display(Name = "Your Name")]
    public string Name { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Your Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(1000, ErrorMessage = "Message should be no more than 1000 characters.")]
    [DataType(DataType.MultilineText)]
    public string Message { get; set; }
}
Hotel Booking System:

Data integrity for date ranges and room types is essential in a hotel booking application.

public class RoomBookingModel
{
    [Key]
    public int BookingId { get; set; }

    [Required]
    [Display(Name = "Guest Name")]
    public string GuestName { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Check-In Date")]
    public DateTime CheckInDate { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Check-Out Date")]
    public DateTime CheckOutDate { get; set; }

    [Required]
    [EnumDataType(typeof(RoomType))]
    [Display(Name = "Room Type")]
    public RoomType TypeOfRoom { get; set; }

    public enum RoomType
    {
        Single,
        Double,
        Suite
    }
}
Library Management System:

Ensuring the right format for ISBN numbers and proper categorization of books is vital for a library system.

public class BookModel
{
    [Key]
    public int BookId { get; set; }

    [Required]
    [Display(Name = "Book Title")]
    public string Title { get; set; }

    [Required]
    [StringLength(13, MinimumLength = 10, ErrorMessage = "ISBN should be 10 or 13 characters long.")]
    [Display(Name = "ISBN Number")]
    public string ISBN { get; set; }

    [Required]
    [Display(Name = "Author")]
    public string AuthorName { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Publication Date")]
    public DateTime PublishedDate { get; set; }

    [EnumDataType(typeof(Genre))]
    [Display(Name = "Book Genre")]
    public Genre BookGenre { get; set; }

    public enum Genre
    {
        Fiction,
        NonFiction,
        Biography,
        Children,
        Mystery,
        Fantasy
    }
}
Employee Portal:

Ensuring accurate data for roles, contact information, and employment dates is critical for a company’s employee portal.

public class EmployeeModel
{
    [Key]
    public int EmployeeId { get; set; }

    [Required]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email Address")]
    public string Email { get; set; }

    [Required]
    [Phone]
    [Display(Name = "Contact Number")]
    public string PhoneNumber { get; set; }

    [Required]
    [EnumDataType(typeof(Role))]
    [Display(Name = "Job Role")]
    public Role EmployeeRole { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Joining Date")]
    public DateTime JoinDate { get; set; }

    public enum Role
    {
        Admin,
        Manager,
        Developer,
        Designer,
        Sales
    }
}
Online Shopping Portal:

When users want to register on an e-commerce site, data annotations can be used to ensure valid and consistent data entry.

public class CustomerRegistrationViewModel
{
    [Required]
    [Display(Name = "Full Name")]
    public string FullName { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email Address")]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [StringLength(12, MinimumLength = 5)]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    [Required]
    [Phone]
    public string PhoneNumber { get; set; }

    [Required]
    [Display(Name = "Shipping Address")]
    public string Address { get; set; }
}
Health Clinic Appointment Booking:

When patients book an appointment, ensure the date and time are specified and gather valid contact information.

public class AppointmentViewModel
{
    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Appointment Date")]
    public DateTime Date { get; set; }

    [Required]
    [DataType(DataType.Time)]
    [Display(Name = "Preferred Time")]
    public DateTime Time { get; set; }

    [Required]
    [Display(Name = "Reason for Visit")]
    public string Reason { get; set; }

    [Required]
    [Phone]
    [Display(Name = "Contact Number")]
    public string ContactNumber { get; set; }
}
Blog Management System:

In a system where users can submit blog posts, data annotations can enforce character limits, ensure necessary fields are filled, and handle other constraints.

public class BlogPostViewModel
{
    [Required]
    [StringLength(200)]
    [Display(Name = "Blog Title")]
    public string Title { get; set; }

    [Required]
    [StringLength(5000)]
    public string Content { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Publish Date")]
    public DateTime PublishDate { get; set; }

    [Display(Name = "Author's Email")]
    [EmailAddress]
    public string AuthorEmail { get; set; }
}
Job Application Portal:

Imagine a scenario where you’re building a job application portal, and applicants need to fill out their details.

public class JobApplicationModel
{
    [Required(ErrorMessage = "Please enter your first name.")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your last name.")]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Invalid Email Address.")]
    public string Email { get; set; }

    [Required]
    [Phone]
    [Display(Name = "Mobile Number")]
    public string PhoneNumber { get; set; }

    [Required]
    [Display(Name = "Position Applying For")]
    public string Position { get; set; }

    [DataType(DataType.Upload)]
    [Display(Name = "Upload Resume")]
    public IFormFile Resume { get; set; }
}
Real Estate Listing:

For a real estate application, agents need to list properties with specific attributes:

public class PropertyListingModel
{
    [Required]
    [Display(Name = "Property Name")]
    public string PropertyName { get; set; }

    [Required]
    [Range(1, 1000, ErrorMessage = "Enter a valid number of rooms.")]
    public int Rooms { get; set; }

    [Required]
    [Display(Name = "Year Built")]
    public int YearBuilt { get; set; }

    [Required]
    [DataType(DataType.Currency)]
    [Range(1, 10000000, ErrorMessage = "Enter a valid price.")]
    public decimal Price { get; set; }

    [MaxLength(1000, ErrorMessage = "Description can't exceed 1000 characters.")]
    public string Description { get; set; }
}
Booking a Workshop or Seminar:

For booking a workshop, attendees might need to provide some details:

public class WorkshopBookingModel
{
    [Required]
    [Display(Name = "Attendee Name")]
    public string AttendeeName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Preferred Date")]
    public DateTime PreferredDate { get; set; }

    [Required]
    [Display(Name = "Workshop Topic")]
    public string Topic { get; set; }
}
Product Review on an E-Commerce Site:

Customers might want to leave reviews for products they’ve purchased:

public class ProductReviewModel
{
    [Required]
    public int ProductId { get; set; }

    [Required]
    [Range(1, 5)]
    public int Rating { get; set; }

    [Required]
    [MaxLength(1000, ErrorMessage = "Review can't exceed 1000 characters.")]
    public string Review { get; set; }

    [Required]
    [Display(Name = "Reviewed By")]
    public string ReviewerName { get; set; }
}
Event Registration Form:

In an event registration form, attendees must provide details to secure a spot.

public class EventRegistrationModel
{
    [Required]
    [StringLength(100, ErrorMessage = "Name should not exceed 100 characters.")]
    [Display(Name = "Attendee Name")]
    public string Name { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Invalid email format.")]
    public string Email { get; set; }

    [Phone(ErrorMessage = "Invalid phone number.")]
    public string PhoneNumber { get; set; }

    [Required]
    [Display(Name = "Choose Event Session")]
    public string Session { get; set; }
}
Order Placement in an E-commerce Platform:

When placing an order, users need to provide shipping details.

public class ShippingDetailsModel
{
    [Required]
    [Display(Name = "Recipient's Name")]
    public string RecipientName { get; set; }

    [Required]
    [StringLength(200, ErrorMessage = "Address is too long.")]
    public string Address { get; set; }

    [Required]
    [RegularExpression(@"^\d{5}$", ErrorMessage = "Invalid zip code.")]
    public string ZipCode { get; set; }

    [Required]
    [Phone]
    [Display(Name = "Contact Number")]
    public string PhoneNumber { get; set; }
}
Gym Membership Form:

For a gym membership registration, data annotations ensure valid user data.

public class MembershipModel
{
    [Required]
    [Display(Name = "Full Name")]
    public string FullName { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Date of Birth")]
    public DateTime DateOfBirth { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [Range(1, 12, ErrorMessage = "Select a valid membership duration.")]
    [Display(Name = "Duration (in months)")]
    public int Duration { get; set; }
}
Feedback for a Restaurant:

After dining in a restaurant, customers might want to leave feedback and rate their experience.

public class RestaurantFeedbackModel
{
    [Required]
    [Display(Name = "Your Name")]
    public string CustomerName { get; set; }

    [Required]
    [Range(1, 5, ErrorMessage = "Please select a rating between 1 and 5.")]
    public int Rating { get; set; }

    [StringLength(500, ErrorMessage = "Feedback should not exceed 500 characters.")]
    public string Feedback { get; set; }

    [EmailAddress(ErrorMessage = "Please provide a valid email address.")]
    [Display(Name = "Email (optional)")]
    public string Email { get; set; }
}

These real-world examples show how data annotations can be employed across various scenarios to handle model validations, guide users in inputting data correctly, and maintain consistency throughout the application in ASP.NET Core MVC.

In the next article, I will discuss Fluent API Validations in ASP.NET Core MVC Applications. In this article, I try to explain Multiple Real-Time Examples of Data Annotations in ASP.NET Core MVC Application. I hope you enjoy this Real-Time Examples of Data Annotations in ASP.NET Core MVC article.

Leave a Reply

Your email address will not be published. Required fields are marked *