CodingFusion

A Complete Guide to Data Annotations in .NET MVC

Required attribute:, stringlength attribute:, range attribute:, regularexpression attribute:, compare attribute:, display attribute:, datatype attribute:, emailaddress attribute:, url attribute:, creditcard attribute:, bind attribute:, fileextensions attribute:, key attribute:, phone attribute:, scaffoldcolumn attribute:, @viewbag.title.

  • Popular Articles
  • Recent Articles

Subscribe for Latest Updates.

ASP.NET MVC Tutorial

  • ASP.NET MVC Tutorial
  • ASP.NET MVC - Home
  • ASP.NET MVC - Overview
  • ASP.NET MVC - Pattern
  • ASP.NET MVC - Environment Setup
  • ASP.NET MVC - Getting Started
  • ASP.NET MVC - Life Cycle
  • ASP.NET MVC - Routing
  • ASP.NET MVC - Controllers
  • ASP.NET MVC - Actions
  • ASP.NET MVC - Filters
  • ASP.NET MVC - Selectors
  • ASP.NET MVC - Views
  • ASP.NET MVC - Data Model
  • ASP.NET MVC - Helpers
  • ASP.NET MVC - Model Binding
  • ASP.NET MVC - Databases
  • ASP.NET MVC - Validation
  • ASP.NET MVC - Security
  • ASP.NET MVC - Caching
  • ASP.NET MVC - Razor

ASP.NET MVC - Data Annotations

  • Nuget Package Management
  • ASP.NET MVC - Web API
  • ASP.NET MVC - Scaffolding
  • ASP.NET MVC - Bootstrap
  • ASP.NET MVC - Unit Testing
  • ASP.NET MVC - Deployment
  • ASP.NET MVC - Self-hosting
  • ASP.NET MVC Useful Resources
  • ASP.NET MVC - Quick Guide
  • ASP.NET MVC - Useful Resources
  • ASP.NET MVC - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of .NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations. DataAnnotation attributes override default Code-First conventions.

System.ComponentModel.DataAnnotations includes the following attributes that impacts the nullability or size of the column.

ConcurrencyCheck

Stringlength.

System.ComponentModel.DataAnnotations.Schema namespace includes the following attributes that impacts the schema of the database.

InverseProperty

Entity Framework relies on every entity having a key value that it uses for tracking entities. One of the conventions that Code First depends on is how it implies which property is the key in each of the Code First classes.

The convention is to look for a property named “Id” or one that combines the class name and “Id”, such as “StudentId”. The property will map to a primary key column in the database. The Student, Course and Enrollment classes follow this convention.

Now let’s suppose Student class used the name StdntID instead of ID. When Code First does not find a property that matches this convention it will throw an exception because of Entity Framework’s requirement that you must have a key property.

You can use the key annotation to specify which property is to be used as the EntityKey.

Let’s take a look at the Student class which contains StdntID. It doesn’t follow the default Code First convention so to handle this, Key attribute is added, which will make it a primary key.

When you run the application and look into the database in SQL Server Explorer, you will see that the primary key is now StdntID in Students table.

Primary Key StdntID

Entity Framework also supports composite keys. Composite keys are primary keys that consist of more than one property. For example, you have a DrivingLicense class whose primary key is a combination of LicenseNumber and IssuingCountry.

When you have composite keys, Entity Framework requires you to define an order of the key properties. You can do this using the Column annotation to specify an order.

Composite Keys

Code First will treat Timestamp properties the same as ConcurrencyCheck properties, but it will also ensure that the database field generated by Code First is non-nullable.

It's more common to use rowversion or timestamp fields for concurrency checking. But rather than using the ConcurrencyCheck annotation, you can use the more specific TimeStamp annotation as long as the type of the property is byte array. You can only have one timestamp property in a given class.

Let’s take a look at a simple example by adding the TimeStamp property to the Course class.

As you can see in the above example, Timestamp attribute is applied to Byte[] property of the Course class. So, Code First will create a timestamp column TStamp in the Courses table.

The ConcurrencyCheck annotation allows you to flag one or more properties to be used for concurrency checking in the database, when a user edits or deletes an entity. If you've been working with the EF Designer, this aligns with setting a property's ConcurrencyMode to Fixed.

Let’s take a look at a simple example and see how ConcurrencyCheck works by adding it to the Title property in Course class.

In the above Course class, ConcurrencyCheck attribute is applied to the existing Title property. Code First will include Title column in update command to check for optimistic concurrency as shown in the following code.

The Required annotation tells EF that a particular property is required. Let’s have a look at the following Student class in which Required id is added to the FirstMidName property. Required attribute will force EF to ensure that the property has data in it.

You can see in the above example of Student class Required attribute is applied to FirstMidName and LastName. So, Code First will create a NOT NULL FirstMidName and LastName column in the Students table as shown in the following screenshot.

Students Table

The MaxLength attribute allows you to specify additional property validations. It can be applied to a string or array type property of a domain class. EF Code First will set the size of a column as specified in MaxLength attribute.

Let’s take a look at the following Course class in which MaxLength(24) attribute is applied to Title property.

When you run the above application, Code-First will create a nvarchar(24) column Title in the Coursed table as shown in the following screenshot.

Column Title Coursed Table

Now when the user sets the Title which contains more than 24 characters, EF will throw EntityValidationError.

The MinLength attribute allows you to specify additional property validations, just as you did with MaxLength. MinLength attribute can also be used with MaxLength attribute as shown in the following code.

EF will throw EntityValidationError, if you set a value of Title property less than the specified length in MinLength attribute or greater than the specified length in MaxLength attribute.

StringLength also allows you to specify additional property validations like MaxLength. The difference being StringLength attribute can only be applied to a string type property of Domain classes.

Entity Framework also validates the value of a property for StringLength attribute. Now, if the user sets the Title, which contains more than 24 characters, then EF will throw EntityValidationError.

Default Code First convention creates a table name same as the class name. If you are letting Code First create the database, you can also change the name of the tables it is creating. You can use Code First with an existing database. But it's not always the case that the names of the classes match the names of the tables in your database.

Table attribute overrides this default convention. EF Code First will create a table with a specified name in Table attribute for a given domain class.

Let’s take a look at an example in which the class is named Student, and by convention, Code First presumes this will map to a table named Students. If that's not the case you can specify the name of the table with the Table attribute as shown in the following code.

You can now see that the Table attribute specifies the table as StudentsInfo. When the table is generated, you will see the table name StudentsInfo as shown in the following screenshot.

Table Name StudentsInfo

You cannot only specify the table name but you can also specify a schema for the table using the Table attribute using the following code.

In the above example, the table is specified with admin schema. Now Code First will create StudentsInfo table in Admin schema as shown in the following screenshot.

StudentsInfo Table in Admin Schema

It is also the same as Table attribute, but Table attribute overrides the table behavior while Column attribute overrides the column behavior. Default Code First convention creates a column name same as the property name.

If you are letting Code First create the database, and you also want to change the name of the columns in your tables. Column attribute overrides this default convention. EF Code First will create a column with a specified name in the Column attribute for a given property.

Let’s take a look at the following example again in which the property is named FirstMidName, and by convention, Code First presumes this will map to a column named FirstMidName. If that's not the case, you can specify the name of the column with the Column attribute as shown in the following code.

You can now see that the Column attribute specifies the column as FirstName. When the table is generated, you will see the column name FirstName as shown in the following screenshot.

Column Name FirstName

The Index attribute was introduced in Entity Framework 6.1. Note − If you are using an earlier version, the information in this section does not apply.

You can create an index on one or more columns using the IndexAttribute. Adding the attribute to one or more properties will cause EF to create the corresponding index in the database when it creates the database.

Indexes make the retrieval of data faster and efficient, in most cases. However, overloading a table or view with indexes could unpleasantly affect the performance of other operations such as inserts or updates.

Indexing is the new feature in Entity Framework where you can improve the performance of your Code First application by reducing the time required to query data from the database.

You can add indexes to your database using the Index attribute, and override the default Unique and Clustered settings to get the index best suited to your scenario. By default, the index will be named IX_<property name>

Let’s take a look at the following code in which Index attribute is added in Course class for Credits.

You can see that the Index attribute is applied to the Credits property. Now when the table is generated, you will see IX_Credits in Indexes.

IX_Credits in Indexes

By default, indexes are non-unique, but you can use the IsUnique named parameter to specify that an index should be unique. The following example introduces a unique index as shown in the following code.

Code First convention will take care of the most common relationships in your model, but there are some cases where it needs help. For example, by changing the name of the key property in the Student class created a problem with its relationship to Enrollment class.

While generating the database, Code First sees the StudentID property in the Enrollment class and recognizes it, by the convention that it matches a class name plus “ID”, as a foreign key to the Student class. But there is no StudentID property in the Student class, rather it is StdntID property in Student class.

The solution for this is to create a navigation property in the Enrollment and use the ForeignKey DataAnnotation to help Code First understand how to build the relationship between the two classes as shown in the following code.

You can see now that the ForeignKey attribute is applied to navigation property.

ForeignKey Attribute

By default conventions of Code First, every property that is of a supported data type and which includes getters and setters are represented in the database. But this isn’t always the case in applications. NotMapped attribute overrides this default convention. For example, you might have a property in the Student class such as FatherName, but it does not need to be stored. You can apply NotMapped attribute to a FatherName property, which you do not want to create a column in a database. Following is the code.

You can see that NotMapped attribute is applied to the FatherName property. Now when the table is generated, you will see that FatherName column will not be created in a database, but it is present in Student class.

FatherName Column Created

Code First will not create a column for a property which does not have either getters or setters.

The InverseProperty is used when you have multiple relationships between classes. In the Enrollment class, you may want to keep track of who enrolled a Current Course and who enrolled a Previous Course.

Let’s add two navigation properties for the Enrollment class.

Similarly, you’ll also need to add in the Course class referenced by these properties. The Course class has navigation properties back to the Enrollment class, which contains all the current and previous enrollments.

Code First creates {Class Name}_{Primary Key} foreign key column if the foreign key property is not included in a particular class as shown in the above classes. When the database is generated you will see a number of foreign keys as seen in the following screenshot.

Number of ForeignKeys

As you can see that Code First is not able to match up the properties in the two classes on its own. The database table for Enrollments should have one foreign key for the CurrCourse and one for the PrevCourse, but Code First will create four foreign key properties, i.e.

  • CurrCourse_CourseID
  • PrevCourse_CourseID
  • Course_CourseID
  • Course_CourseID1

To fix these problems, you can use the InverseProperty annotation to specify the alignment of the properties.

As you can see now, when InverseProperty attribute is applied in the above Course class by specifying which reference property of Enrollment class it belongs to, Code First will generate database and create only two foreign key columns in Enrollments table as shown in the following screenshot.

ForeignKey Enrollments Table

We recommend you to execute the above example for better understanding.

Table of Contents

Data annotation attributes in asp.net mvc, why do we need data annotation attributes in asp.net mvc, what are the validations, built-in validation attributes, enabling client-side validation in asp.net mvc application.

Data Annotations in MVC

In ASP.NET MVC , Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes. Data Annotations accommodate us to establish the controls to the model properties or classes for data validation and performing applying messages to users. In this article, we will understand the concepts of data annotation in MVC.

Want a Top Software Development Job? Start Here!

Want a Top Software Development Job? Start Here!

Here are the numerous types of Data Annotations with the syntax:

1) DataType

This attribute is used to specify the data type of the model.

[DataType(DataType.Text)]

2) Required

This attribute defines the particular value as mandatory for a certain requirement 

[Required(ErrorMessage="Please enter your name"),MaxLength(50)]

3) StringLength

Using this annotation attribute, we can set the maximum and minimum string range of the property.

[StringLength(50,ErrorMessage="Please do not enter values over 50 characters")]

4) MaxLength

With this annotation attribute, we can set the maximum length of the property.

[MaxLength(5)]

We can apply the Range annotation attribute to define the range between two numbers.

[Range(50,250,ErrorMessage="Please enter the correct value")]

This annotation attribute defines fields to enter or eliminate for model binding.

[Bind(Exclude = "EmployeeID")]

7) DisplayFormat

This annotation attribute enables us to set the date format defined as per the attribute.

[DisplayFormat(DataFormatString = "{0:MM.DD.YYYY}")]

8) DisplayName

With this annotation attribute we can set the property names that will  display at the view.

[Display(Name="Employee Name")]

9) RegularExpression

Using this attribute, we can set a regex (regular expression) pattern for the property. For example, Email ID.

[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Your Email is not valid.")]

10) ScaffoldColumn

Specifies whether scaffolding is used by a class or a data column.

[System.AttributeUsage(System.AttributeTargets.Field |    System.AttributeTargets.Property, AllowMultiple=false)]

public class ScaffoldColumnAttribute : Attribute

In Data Annotations, we have two types of namespaces that have their specific in-build types.

1. System.ComponentModel.DataAnnotations incorporate the subsequent attributes that affect and check the size or nullability of the column.

  • StringLength
  • ConcurrencyCheck

2. System.ComponentModel.DataAnnotations.Schema namespace comprises the subsequent attributes that reshape the schema of the database.

  • InverseProperty

In ASP.NET MVC web applications, we have the three types of data validations:

Client-Side Validation: HTML / JavaScript validation

Server-side Validation:

  •    ASP.NET MVC Model validation 
  •    Database validation

Here we have ASP.NET MVC model validation that is a more secure validation whereas HTML/JavaScript validation is unsafe and can break after disabling the javascript while running the application.

ASP.NET MVC Framework implements a framework described as Data Annotation which is utilized for model validation. It is derived from System.ComponentModel.DataAnnotations assembly.

We can use Data Annotation to implement the model validation and can utilize it to model class properties.

Validation is the set of rules which we define on the input fields on the webform page. We have certain types of validations which we can use as per the user requirements:

  • Client-Side Validation
  • Server-side Validation

In ASP.NET MVC , we have a System.ComponentModel.DataAnnotations assembly which has several built-in validation types of attributes’ properties which we can implement as per the code logic.

  • RegularExpression
  • Credit Card number
  • Multi-line text
  • Date or DateTime
  • Email Address
  • Phone number
  • Postal Code

In ASP.NET MVC, we can consider Built-in validation attributes as custom validation. Below are a few examples:

  • Compare: It validates and matches two fields' properties in a model.
  • Range: It validates when a certain property value comes into a certain range.
  • RegularExpression: It validates when a property value meets a certain regular expression.
  • Remote: It works on a remote validation; we can call an action method function on the server and validate specific inputs on the client's side.
  • DevExtremeRequired: It validates when the certain boolean property value is true or false.
  • Custom : It allows you to define a custom validation attribute.

To enable the client-side validation, we can use JQuery and Javascript. Before using it, we should take the reference of the JavaScript files from the Scripts folder of your .net solution.

Example: jquery.validate.unobtrusive.js and query.validate.min.js 

Below is the layout example:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>@ViewBag.Title - Example Data annotation in MVC Application</title>

    @Styles.Render("~/Content/css") 

    @Scripts.Render("~/bundles/modernizr")

</head>

<body>

     @Html.Partial("_HeaderNavBar");   

    <div class="container body-content">

        @RenderBody()        

        <hr />

        <footer>

            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>

        </footer>

    </div>

    @Scripts.Render("~/bundles/jquery")

    @Scripts.Render("~/Scripts/jquery.validate.min.js")

    @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")

    @Scripts.Render("~/bundles/bootstrap")

    @RenderSection("scripts", required: false)

</body>

</html>

Advance your career as a MEAN stack developer with the  Full Stack Web Developer - MEAN Stack Master's Program . Enroll now!

We hope this article helped you understand Data Annotation in MVC using C# . In this article, we discussed the concept of data annotation and its various types, and validations with examples that will be helpful to professional developers from Java and .net backgrounds, application architectures, and other learners looking for information on JavaScript events.

Besides pursuing varied courses provided by Simplilearn, you can also sign up on our SkillUp platform . This platform, a Simplilearn initiative, offers numerous free online courses to help with the basics of multiple programming languages , including JavaScript. You can also opt for our Full-Stack Web Development Certification Course to improve your career prospects.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Recommended Reads

Data Science Career Guide: A Comprehensive Playbook To Becoming A Data Scientist

All You Need to Know About the Architecture of MVC

ASP.NET MVC

Big Data Career Guide: A Comprehensive Playbook to Becoming a Big Data Engineer

What Is Image Annotation and Why Is It Important in Machine Learning

The All Time Best Tutorial to Understand ASP.NET Core MVC

Get Affiliated Certifications with Live Class programs

Caltech post graduate program in ai and machine learning.

  • Earn a program completion certificate from Caltech CTME
  • Curriculum delivered in live online sessions by industry experts

Full Stack Web Developer - MEAN Stack

  • Comprehensive Blended Learning program
  • 8X higher interaction in live online classes conducted by industry experts

Post Graduate Program in Full Stack Web Development

  • Live sessions on the latest AI trends, such as generative AI, prompt engineering, explainable AI, and more
  • Caltech CTME Post Graduate Certificate
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Live Training, Prepare for Interviews, and Get Hired

  • Learn ASP.NET MVC5 Step By Step Crash Course 2024
  • Getting Started with MVC5 with Visual Studio 2024
  • Top MVC 5 Interview Questions & Answers | MVC5 Interview Q&A for Beginners
  • A Brief History of ASP.NET MVC Framework
  • Introduction to ASP.NET MVC
  • Difference Between Razor View Engine and ASPX View Engine
  • Enable jQuery Intellisense support to MVC3 Razor
  • ASP.NET Development Models
  • Difference between ASP.NET WebForms and ASP.NET MVC

Intermediate

  • Understanding Internationalization in ASP.NET MVC
  • Understanding AJAX Helpers in ASP.NET MVC
  • Understanding HTML Helpers in ASP.NET MVC
  • Persisting Data with TempData
  • Understanding ASP.NET MVC Filters and Attributes
  • Changing browser URL with jQuery mobile and Asp.Net MVC
  • Custom Validation for Cascading Dropdownlist in MVC Razor
  • How to get textboxes values in MVC4 created by jQuery
  • Html submission by ValidateInput and AllowHtml attribute in MVC4
  • Exception or Error Handling and Logging in MVC4
  • Enhancing WebGrid with Insert Update and Delete Operations
  • WebGrid with custom paging and sorting in ASP.NET MVC
  • Enhancing WebGrid with ajax in MVC4
  • File upload with strongly typed view and model validation
  • Understanding Model View Controller in ASP.NET MVC
  • Asp.net MVC 4 performance optimization with bundling and minification
  • Routing in Asp.Net MVC with example
  • Route Constraints in Asp.Net MVC with example
  • MVC Areas with example
  • Custom Validation for Checkbox in MVC Razor
  • Controlling Session Behavior in Asp.Net MVC4
  • Resolve Ambiguous Controller Error by routes
  • ASP.NET MVC Registration form with Validation
  • RenderPartial vs RenderAction vs Partial vs Action in MVC Razor
  • Bundling and minification in MVC3 and Asp.Net 4.0
  • Understanding Controllers and Actions in MVC Razor
  • Setting default submit button in MVC3 razor using jQuery
  • ASP.NET MVC - View() vs RedirectToAction() vs Redirect() Methods
  • Understanding ViewModel in ASP.NET MVC
  • Understanding Attribute Routing in ASP.NET MVC
  • ViewData vs ViewBag vs TempData vs Session
  • How to Enable and Disable Client-Side Validation in MVC
  • Partial View in ASP.NET MVC
  • How to upload a file in ASP.MVC
  • Layouts, RenderBody, RenderSection and RenderPage in ASP.NET MVC

MVC Data Annotations for Model Validation

  • Server Side Model Validation in MVC Razor
  • Different ways of rendering layouts in Asp.Net MVC
  • Inline CSS and Styles with Html Helpers in MVC3 Razor
  • Understanding ASP.NET MVC Scaffolding
  • Handling multiple submit buttons on the same form - MVC Razor
  • Implementing Repository and Unit of Work Patterns with ASP.NET MVC
  • Detailed ASP.NET MVC Pipeline
  • Donut Caching and Donut Hole Caching with Asp.Net MVC 4
  • Custom Razor View Engine for C# and VB
  • Understanding Caching in Asp.Net MVC with example
  • Securing Asp.Net MVC Application by using Authorize Attribute
  • CRUD Operations using jQuery dialog, Entity Framework and ASP.NET MVC
  • Removing the Web Form View Engine for better performance of Razor View Engine
  • Custom Authentication and Authorization in ASP.NET MVC
  • Asp.net MVC Request Life Cycle
  • Top 25+ MVC Interview Questions and Answers

Live Training

  • ASP.NET Core Certification Training
  • Azure Developer Certification Training
  • .NET Microservices Certification Training
  • MVC Data Annotations For ..
  • YouTube Videos
  • Interview eBooks
  • Training Library

MVC Data Annotations for Model Validation

MVC Data Annotations: An Overview

In this MVC Tutorial , we are going to explore Data Annotations. Data validation is a key aspect of developing web applications. In Asp.net MVC, we can easily apply validation to web applications by using Data Annotation attribute classes to model classes. Data Annotation attribute classes are present in the System.ComponentModel.DataAnnotations namespace and are available to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms, and also to Entity framework orm models.

Data Annotations help us to define the rules for the model classes or properties for data validation and display suitable messages to end users.

Data Annotation Validator Attributes

Specify the datatype of a property

DisplayName

specifies the display name for a property.

DisplayFormat

specify the display format for a property like a different format for a Date property.

Specify a property as required.

Regular expression

validates the value of a property by a specified regular expression pattern.

validate the value of a property within a specified range of values.

StringLength

specifies min and max length for a string property.

specifies the max length for a string property.

specify fields to include or exclude when adding parameter or form values to model properties.

ScaffoldColumn

specifies fields for hiding from editor forms.

Designing the model with Data Annotations

Once we have defined validation to the model by using data annotations, these are automatically used by HTML Helpers in views. For client-side validation to work, please ensure that below two <SCRIPT> tag references are in the view.

Presenting the model in the view

In this article, I try to expose the Data Annotations with examples. I hope you will refer to this article for your needs. I would like to have feedback from my blog readers. Please post your feedback, questions, or comments about this article. Enjoy Coding..!

Unlock the next level of MVC:

Q1. can we do validation in mvc using data annotations, q2. which attributes can be used for data validation in mvc, q3. why do we use @valid annotation, take our free skill tests to evaluate your skill.

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.

About Author

Author image

ASP.NET MVC Questions and Answers Book

ASP.NET MVC is an open source and lightweight web application development framework from Microsoft. This book has been written to prepare yourself for ASP.NET MVC Interview. This book is equally helpful to sharpen their programming skills and understanding ASP.NET MVC in a short time. This book also helps you to get an in-depth knowledge of ASP.NET MVC with a simple and elegant way.

AngularJS Questions and Answers Book

AngularJS Questions and Answers Book

In this book, we will be discussing the top AngularJS interview questions and answers. We will also provide tips on how to best prepare for an interview. In this book, we’ll provide a list of AngularJS interview questions for experienced developers as well as freshers. We'll also provide tips on how to best prepare for your interview. You can download AngularJS interview questions and answers pdf. With this book, you'll have everything you need to make the best impression possible and land the job of your dreams!

ASP.NET Core Questions and Answers Book

ASP.NET Core Questions and Answers Book

ASP.NET Core is an open source and cross-platform framework used for building Web Applications, Cloud-based applications, IoT Applications, and also Mobile applications using C# and .NET. It was developed by Microsoft to allow programmers to build dynamic web sites, web services and web applications. ASP.NET Core runs on Windows, macOS, and Linux.

WCF and Web Services Questions Book

WCF and Web Services Questions Book

There are a lot of WCF interview questions and answers. In order to help you prepare for your interview, we have put together a list of the most common WCF interview questions and answers. This book will help you understand the key concepts behind WCF and give you the tips and tricks you need to answer these questions confidently. We’ll provide a list of WCF interview questions for experienced as well as fresher’s. So, don't wait any longer - download the WCF interview questions and answers pdf now and start preparing for your interview!

HR Questions and Answers Book

HR Questions and Answers Book

If you’re preparing for a job interview in the Human Resources field, then you need to be prepared to answer some common HR interview questions and answers. The best way to do that is to practice beforehand. But where can you find good HR interview questions and answers? One great resource is this book called "HR Interview questions and answers." This book provides detailed explanations of what employers are looking for when they ask each question, as well as sample responses. We’ll provide a list of HR interview questions for freshers as well as experienced developers. You can just download the HR interview questions and answers pdf. Happy job hunting!

Entity Framework 6.x Questions and Answers Book

Entity Framework 6.x Questions and Answers Book

Entity Framework is a powerful tool for data access in .NET applications. It can be used to query and manipulate data, as well as to persist changes back to the database. If you are looking for a job as an Entity Framework developer then you need to be prepared for the interview questions. In this book, we will review some of the most common Entity Framework interview questions and answers to help you prepare. We will provide you with Entity Framework interview questions and answers pdf. We hope that this information will help you prepare for your interview. Happy coding!

ASP.NET Web API Questions and Answers Book

ASP.NET Web API Questions and Answers Book

If you’re preparing for an interview for a job that requires ASP.NET Web API experience, then you will want to be sure to go over the ASP.Net Web API interview questions and answers in this book. It includes detailed explanations of how to answer common questions, as well as tips on what to do if you get stuck. Going over these ASP.Net Web API interview questions and answers will help make sure you are ready for your interview. The answers will give you the confidence you need to ace your next interview. You just have to download the ASP.Net Web API interview questions and answers pdf. Best of luck!

  • Apache Hadoop, Hadoop, and Apache logo are either registered trademarks or trademarks of the Apache Software Foundation.
  • Android, Android Logo, Google, Google Cloud and its products are either registered trademarks or trademarks of Google, Inc.
  • AWS, Amazon Web Services and its products are either registered trademarks or trademarks of Amazon Web Services, Inc.
  • Certified ScrumMaster (CSM) and Certified Scrum Trainer (CST) are registered trademarks of SCRUM ALLIANCE
  • iPhone, iOS and Apple are the registered trademarks or trademarks of Apple Inc.
  • Microsoft, Microsoft Azure and its products are either registered trademarks or trademarks of Microsoft Corporation.
  • MongoDB, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.
  • Oracle, Java, and Primavera are the registered trademarks of Oracle Corporation.
  • Python and the Python logos (in several variants) are the trademarks of the Python Software Foundation.
  • "PMP","PMI", "PMI-ACP" and "PMBOK" are registered marks of the Project Management Institute, Inc.
  • Salesforce and the respective Salesforce logos are the registered trademarks of Salesforce.com
  • Other brands, product names, trademarks, and logos are the property of their respective companies.

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

what is data annotation in mvc

Implement Data Validation in MVC

Here, you will learn how to implement the data validation and display validation messages on the violation of business rules in an ASP.NET MVC application.

The following image shows how the validation messages will be displayed if Name or Age fields are blank while creating or editing data.

Display Validation Messages

Validation using Data Annotation Attributes

ASP.NET MVC includes built-in attribute classes in the System.ComponentModel.DataAnnotations namespace. These attributes are used to define metadata for ASP.NET MVC and ASP.NET data controls. You can apply these attributes to the properties of the model class to display appropriate validation messages to the users.

The following table lists all the data annotation attributes which can be used for validation.

Let's see how to use these attributes to display validation messages on the view.

The following is the Student model class.

We want to implement validations for StudentName and Age property values. We want to make sure that users do not save empty StudentName or Age value. Also, age should be between 10 to 20.

The Required attribute is used to specify that the value cannot be empty. The Range attribute is used to specify the range of values a property can have. We will use the Required attribute on the StudentName to make it mandatory for the user to provide value and Range attribute to make sure the user enters value between 10 to 20, as shown below.

The above attributes define the metadata for the validations of the Student class. This alone is not enough for the validation. You need to check whether the submitted data is valid or not in the controller. In other words, you need to check the model state.

Use the ModelState.IsValid to check whether the submitted model object satisfies the requirement specified by all the data annotation attributes. The following POST action method checks the model state before saving data.

Now, create an edit view as shown here . The following is a generated edit view using the default scaffolding template.

In the above view, it calls the HTML Helper method ValidationMessageFor() for every field and ValidationSummary() method at the top. The ValidationMessageFor() displays an error message for the specified field. The ValidationSummary() displays a list of all the error messages for all the fields.

In this way, you can display the default validation message when you submit a form without entering StudentName or Age , as shown below.

what is data annotation in mvc

Learn how to implement client side validation in ASP.NET MVC .

.NET Tutorials

Database tutorials, javascript tutorials, programming tutorials.

Dot Net Tutorials

Data Annotation Attributes in ASP.NET Core MVC

Back to: ASP.NET Core Tutorials For Beginners and Professionals

In this article, I will discuss How to Perform Model Validations using Data Annotation Attributes in ASP.NET Core MVC Application with Examples. Please read our previous article discussing Model Validations in ASP.NET Core MVC .

Required Data Annotation Attribute in ASP.NET Core MVC

Let’s understand the Required Data Annotation Attribute with one example. Our business requirement is that an employee’s First Name and Last Name can’t be empty. That means we will force the user to give the first and last names; we can achieve this very easily in the ASP.NET Core MVC application by decorating the FirstName and LastName model properties with the Required data annotation attribute. The Required attribute makes the model property as required.

Next, modify the Employee Controller as follows:

Next, modify the Create.cshtml view as follows:

The Required attribute raises a validation error if the property value is null or empty. The built-in required validation attributes provide both client-side and server-side validation. When we submit the page without providing the first name and last name of an employee, we will get the error message as shown in the below image.

Required Data Annotation Attribute in ASP.NET Core MVC

With the required attributes in place, if someone tries to submit the page without providing the FirstName and LastName values, it will give us the default error, as shown in the above image. But suppose you want to provide some user-defined error message when validation fails. In that case, you can use the other overloaded version of the Required attribute, which accepts ErrorMessage as an input parameter, as shown below.

With the above changes, if someone tries to submit the page without providing the FirstName and LastName values, it will give the user-defined error message, as shown in the image below.

How to Perform Model Validations using Data Annotation Attributes in ASP.NET Core MVC Application with Examples

StringLength Data Annotation Attribute in ASP.NET Core MVC

In our last example, we are forcing the user to enter his first name and last but what happens if he enters a name with enormous length? For example, our business requirement is that the employee’s last name should not be greater than 30 characters, which means we need to set a maximum of 30 characters that can be entered for the employee’s last name. We can easily achieve this using the StringLength data annotation attribute in the ASP.NET Core MVC application. To achieve this, we must decorate the LastName property with the StringLength attribute, as shown below.

With the above changes in place, it will not allow you to enter more than 30 characters in the Last Name text box, as shown in the below image.

StringLength Data Annotation Attribute in ASP.NET Core MVC

The [StringLength] attribute verifies that a string is of a certain length but does not enforce that the property is  REQUIRED . If you want to enforce that the property is required, use the [Required]  attribute.

We can also apply multiple validation attributes on a single property. The MinimumLength is an optional named parameter used to specify a string’s minimum length. We can also specify the user-defined error message. Here, we specify the minimum length as 4 and the ErrorMessage as the Last name should be between 4 and 30 characters.

In the above example, we have decorated the LastName   property with the  StringLength  attribute and then specified the  Minimum  and  Maximum  length of the model properties. We also used the  [Required] attribute. So, at this point, the LastName property is required and should be between 4 and 30 characters. Now run the application and check everything is working as expected, as shown below.

How to Perform Model Validations using Data Annotation Attributes in ASP.NET Core MVC Application with Examples

RegularExpression Data Annotation Attribute in ASP.NET Core MVC:

The Regular Expression Attribute is generally used for pattern-matching validations in ASP.NET Core MVC applications. Let’s understand the Regular expression attribute with an example. Suppose we need to validate the Email ID of an employee; then we can achieve this very easily in the ASP.NET MVC application by using Regular expression attributes as shown below:

Next, modify the Create.cshtml view as follows.

In the above example, we are applying both Required and RegularExpression attributes to the EmailID model property, which ensures that the Email ID is a required field and will validate the Email ID field value, as shown below. When a user tries to enter an invalid Email ID and submit the page, he will get the validation error message as shown below.

RegularExpression Data Annotation Attribute in ASP.NET Core MVC

User Name Validation Example:

Here is the requirement for validating the Name property

  • UserName can contain the first and last names with a single space.
  • The last name is optional. If the last name is absent, there shouldn’t be any space after the first name.
  • Only upper and lower-case alphabets are allowed.

This requirement can be achieved very easily in ASP.NET Core MVC using RegularExpressionAttribute. In the Employee.cs class file, decorate the UserName property with the RegularExpression attribute as shown below.

Notice that we are passing a regular expression string to the Attribute constructor. The Regular Expression Attribute is great for pattern matching and ensures that the value for the UserName property is in the format we want. Also, we use a verbatim literal (@ symbol) string, as we don’t want escape sequences to be processed. Next, modify the Create.cshtml file as follows.

Run the application and see the UserName field is working as expected.

How to Perform Model Validations using Data Annotation Attributes in ASP.NET Core MVC Application with Examples

Understanding and writing regular expressions is beyond the scope of this article. If you are interested in learning to write regular expressions, here is a link from MSDN

http://msdn.microsoft.com/en-us/library/az24scfc.aspx

Range Data Annotation Attribute in ASP.NET Core MVC:

Suppose we have the Age field in the Employee model. If we don’t provide any validations, then we can enter any value, such as 5000, as the age, and click on the Save button, then the data also gets saved.

As we know, an employee 5000 years of age is not possible. So, let’s validate the Age field and force users to enter a value between 18 and 60. We can achieve this easily using the RangeAttribute in ASP.NET Core MVC Application. The Range attributes specify a numerical number’s minimum and maximum constraints, as shown below.

In the above example, we set the employee’s age to be between 18 and 60 years to pass the validation. Here, the first parameter of the attribute is the minimum value, the second parameter is the maximum value, and the third parameter is the error message we want to show when the validation fails. Next, modify the Create.cshtml view as follows:

When a user tries to enter the age which is not between 18 and 60 and clicks on the submit button, then he will get the validation error message as shown below:

Range Data Annotation Attribute in ASP.NET Core MVC

At this point, we should not be able to enter any values outside the range of 18 and 60 for the Age field.

Note: The Range attribute in ASP.NET Core MVC does not support the validation of the DateTime fields.

MinLength and MaxLength Attribute in ASP.NET Core MVC:

These two attributes specify the Minimum and Maximum Length of a property. For example, suppose we want to restrict the Employee Address as 5 as the minimum length and 25 as the maximum length. In that case, we can decorate the address property with the MinLength and Maxlength attributes, as shown below.

Next, modify the Create.cshtml file as follows.

Submitting the page by entering less than 5 characters will give the error as shown below.

MinLength and MaxLength Attribute in ASP.NET Core MVC

DataType Attribute in ASP.NET Core MVC:

DataType Attribute in ASP.NET Core MVC Framework enables us to provide the runtime information about the specific purpose of the properties. For example, a property of type string can have various scenarios, as it might hold an Email address, URL, or password. Data types include Currency, URL, Phone, Date, Time, Password, etc. If you go to the definition of DataType Enum, you will see the following named constants that we can specify using the DataType Attribute.

DataType Attribute in ASP.NET Core MVC

Let’s see examples of using the DataType attribute in the ASP.NET Core MVC Application. Please modify the Employee model class as follows.

Compare Data Annotation Attribute in ASP.NET MVC Application:

Compare Attribute in ASP.NET Core MVC Framework is used to compare 2 model properties with the same value. Comparing credit card numbers and passwords is the common use case of the Compare attribute. Let’s understand using the Compare attribute with an example. For example, to ensure that the user has typed the correct password, we must use the Password and ConfirmPassword of the employee model, as shown below.

Now, if both Password and Confirm Password are not the same, the user will get the model validation error, as shown below:

Compare Data Annotation Attribute in ASP.NET MVC Application

Complete Example:

Let us put all the validation into a single model. So, modify the Employee.cs class file as follows.

Create.cshtml:

In the next article, I will discuss How to Create Custom Data Annotations in ASP.NET Core MVC Applications with Real-Time Examples. In this article, I try to explain Data Annotation Attributes in ASP.NET Core MVC with Examples. I hope you enjoy this Data Annotation Attributes in ASP.NET Core MVC article.

dotnettutorials 1280x720

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

Leave a Reply Cancel reply

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

QAWithExperts.Com logo

  • Ask a question
  • Contribute an article
  • Amazon Web server
  • Mobile developement
  • Windows/MacOsx
  • Minify HTML online
  • Minify CSS online
  • Minify JS (Javascript) online
  • Online HTML formatter (Beautifier)
  • Online CSS Beautifier
  • Online JS (Javascript) Formatter
  • Online XML Formatter
  • Online SQL formatter

Data annotation in ASP.NET MVC (Example with creating Custom Validation)

Previously I had provided a sample article about Form Submit in ASP.NET MVC using HTML.BeginForm , but if you are working in ASP.NET MVC and need to validate the form on the server-side other than client-side form validation using Javascript , then you have landed on the right place, as we can do this using data annotation in C# or you can say using ASP.NET MVC data annotation.

There is possible to validate the form using various jQuery plugins or custom jQuery/Javascript, but it is always essential to validate Model(form data) on the server-side as anyone disrupts/bypass client-side validation, so always make sure to implement server-side validations.

To make server-side validations possible in ASP.NET MVC we use Data Annotation while creating a Model, which help us in verifying if data input by user is correct and as per what we need.

What is Data Annotation in C#?

In ASP.NET MVC application we can do the Server Side Validation on the Model using Data Annotations .

Data Annotations is a namespace, providing attribute classes, which are used to define metadata for controls. Data Annotations allow us to describe the rules we want to be applied to our model properties, and ASP.NET MVC will take care of enforcing them and displaying appropriate messages to our users.

MVC Provides a large number of Data Annotations class. Some important ones are:

  • [Required] – Indicates that the property is a required field
  • [DisplayName] – Defines the text we want to be used on form fields and validation messages
  • [StringLength] – Defines a maximum length for a string field
  • [Range(int minimum, int maximum)] – Gives a maximum and minimum value for a numeric field
  • [Bind] – Lists fields to exclude or include when binding parameter or form values to model properties
  • [ScaffoldColumn] – Allows hiding fields from editor forms
  • [RegularExpression(string pattern)]  - Data field value must match the specified regular expression pattern.
  • [EmailAddress] - The value must be an email address.
  • [Phone] - The value must be phone number.

Validating form using Data Annotation in ASP.NET MVC

Let's create a simple form with basic details, to check how can we implement server-side validation in ASP.NET MVC using Data annotation.

Step 1: Create a MVC project in your Visual Studio, by navigating to File -> New -> Project (Select 'Web' from left pane &  Select 'ASP.NET web application' from right pane)

Enter the name of your project(DataAnnotationMVC) and click "Ok"

Now select MVC template to generate default layout.

Step 2:  Create Model with properties which we need to save in database( we will not consider saving details in the database in this article, just validating the Model )

Let's create a Student.cs Model by right-clicking on Models folders and add a new class.

now in the above Model, we have just created the Model with properties, let's add some Data Annotation attributes( few of the above mentioned ) to validate all the fields.

I will describe each field data annotation now.

Name:  A required field, just provide Required attribute to it.

Age: Age field is also required , but we also need to impose range field as Age must be greater than 20 while it should be above 10

Email:  Making this field also as Required, but we will more data annotation in it, like Display(Name="Email address")  which is used to display the label text in Razor form, another data annotation will be  EmailAddress  attribute with error message described

BirthDate:  Must be a data and between 01-25-1998 & 01-25-2008. So, for this field, I have provided 2 attributes –

a. DataType for specifying it to be of date time.

b. A custom attribute through which I do the manual server-side validation.

Now before we proceed, let's create the Custom Validation

Creating Custom Validation in MVC

We can easily create custom validation data annotation in MVC by deriving ValidationAttribute class and then overriding IsValid method which returns ValidationResult for this example.

So, right-click on your projects Model Folder, create a new class, Name it "ValidateBirthDate" 

So, your complete Model with data annotation will look like below

Now, we have created the Model and added all the validation, with one Custom Attribute also, let's use them in our Form now.

Step 3: Create a ActionMethod which returns Create's Student and another to validate and save Form data in the database or return the Create View with validation errors.

So navigate to HomeController.cs inside Controller folder and create the two ActionMethod as described above

Step 4: Add the Create View, right-click inside Create ActionMethod and select "Add View", now you need to add the proper Razor HTML to add fill form data and show Validation error message where required.

For showing validation of each method, we will use HTML helper @Html.ValidationMessageFor(), we can also show all form errors at once using  @Html.ValidationSummary()

So, here is the Razor code for adding data in input field's which shows error message below the text box

Step 5: Build your project and navigate to "http://localhost:50656/Home/Create" page to create Student and check Validation's, the output will be as below

data-annotation-in-mvc-min.png

When I tried to submit form without adding any data

data annotation validation in MVC

Now, When I tried to add some data and some with wrong details

filling-wrong-values-min.png

Here is the Gif image which shows different errors.

I haven't added correct email, just to hide my email in gif(not a good gif editor), but you can test it on your own, it should work.

Feel free to add comment below or ask questions related this article in questions section by linking it.

You may also like to read: Model Validation in ASP.NET Core MVC (With Custom validation example) Creating Google charts in ASP.NET Core MVC Best .NET APM tools to consider for your .NET application Read OR Generate QR Code in ASP.NET Core Export to Excel C# GridView in ASP.NET Web-Form HTML to PDF using iTextSharp OR Rotativa in MVC C# (Examples)

Comment's

profileImage

I was looking for MVC articles like this, thanks

Related Articles

Subscribe now.

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly

Related Questions

what is data annotation in mvc

20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management

Onur Derman

Onur Derman

Level Up Coding

Data annotations in ASP.NET Core are attributes that can be applied to model properties to define validation rules, format strings, and other metadata. They are a key feature of the .NET framework and can help make your code more efficient, easier to maintain, and more secure. In this article, we will discuss 20 of the most important data annotations in ASP.NET Core, along with detailed explanations and code examples.

Important Note: In this article I will demonstrate 20 important data annotations, first with independent examples and then at the end of the article you can find one sample entity class — Employee — in which I implement all the data annotations in the same class. Have a nice reading :)

Why and When to Use Data annotations

Data annotations (DAs) are used to provide metadata to your code, which can help to control the behavior of your code. By using DAs in your code, you can ensure that your application is more robust, reliable, and maintainable.

Here are some reasons why and when you might use data annotations:

  • Data Validation — DAs can be used to enforce data validation rules, ensuring that data entered into your application meets certain requirements. For example, the [Required] annotation can be used to ensure that a property is not null or empty, and the [Range] annotation can be used to ensure that a numeric property falls within a specific range.
  • Display Formatting — DAs can be used to control how data is displayed in your application’s user interface. For example, the [DisplayFormat] annotation can be used to control the formatting of a date or time property.
  • Data Mapping — DAs can be used to specify how your entity is mapped to the database. For example, the [Key] annotation can be used to specify the primary key for your entity, and the [ForeignKey] annotation can be used to specify the foreign key for a navigation property.
  • Model Binding — DAs can be used to control how data is bound to your application’s model. For example, the [Bind] annotation can be used to specify which properties should be included or excluded when binding to a model.
  • Concurrency Control — DAs can be used to handle concurrency issues when updating data. For example, the [Timestamp] annotation can be used to include a timestamp property in your entity, which can be used to detect when data has been modified by another user.

After a quick brief, let’s jump into each one of them separately in independent examples.

1- Required

The Required data annotation is used to mark a property as required. This means that the property cannot be null or empty. If the property is not set, a validation error will be raised.

The Range data annotation is used to define a range for numeric properties. You can specify the minimum and maximum values for the property.

3- StringLength

The StringLength data annotation is used to define the maximum length of a string property.

4- RegularExpression

The RegularExpression data annotation is used to validate a property against a regular expression pattern. It is used to apply a regular expression pattern to a string property in an ASP.NET Core model class. In this case, the regular expression pattern specifies that the string must consist only of alphanumeric characters (letters and digits).

5- EmailAddress

The EmailAddress data annotation is used to validate an email address. You can use it to ensure that the email address entered by the user is in a valid format:

6- CreditCard

The CreditCard data annotation is used to validate a credit card number. You can use it to ensure that the credit card number entered by the user is in a valid format:

7- DataType

The DataType data annotation is used to specify the data type of a property.

In this example I used DataType.DateTime but there are other data types that can be specified using the [DataType] attribute in ASP.NET Core. Here are some of the most commonly used ones:

DataType.Date, DataType.Time, DataType.Duration, DataType.Password, DataType.MultilineText, DataType.PhoneNumber, DataType.Url, DataType.Currency …

The Display data annotation is used to set the display name for a property in an ASP.NET Core model class. It’s used to specify the name of the property that should be displayed in user interfaces instead of the property name itself.

In the example below, it indicates that the property should be displayed as “Product Name” in user interfaces, instead of “Name”.

9- DisplayFormat

The DisplayFormat data annotation is used to specify the format of a property for display purposes. For example, if the property value is 100.50, it will be displayed as "$1,000.50" if the current culture uses the dollar sign as the currency symbol.

10- Compare

The Compare data annotation is used to compare two properties. We generally use it to confirm the passwords in register pages.

The Remote data annotation is used to perform remote validation of a property. This can be useful for validating uniqueness, for example.

12- ScaffoldColumn

The ScaffoldColumn data annotation is used to specify whether a property should be included in the scaffolded views. If you have a scaffold page that lists the products, the Id property will be excluded in the List View Page.

13- ForeignKey

The ForeignKey data annotation is used to specify a foreign key relationship.

14- DisplayColumn

The DisplayColumn data annotation is used to specify the default column to use for display purposes.

By setting the [DisplayColumn(“FullName”)] attribute, you are telling ASP.NET Core to use the FullName property as the default column to display when scaffolding views for the Person model class.

The Bind data annotation is used to specify which properties of a model should be included in model binding.

In this example only Firstname, LastName and Email properties will be passed to the Create method inside customer parameter.

16- HiddenInput

The HiddenInput data annotation is used to specify that a property should be rendered as a hidden input field.

In the code above, the Order class has an Id property decorated with the [HiddenInput] attribute, which means that it will not be displayed in any form generated by ASP.NET Core.

17- DisplayOrder

The DisplayOrder data annotation is used to specify the order in which properties should be displayed.

18- Timestamp

The Timestamp data annotation is used to specify that a property should be used for optimistic concurrency checking.

In this example, the Timestamp property is decorated with the [Timestamp] attribute. This tells ASP.NET Core to use this property to perform optimistic concurrency checks when updating records in the database.

Optimistic concurrency is a technique used to prevent two users from updating the same record at the same time and overwriting each other’s changes. When you perform an update operation on a record with a timestamp property, ASP.NET Core will compare the timestamp value of the record in the database with the timestamp value that you provide in your update operation. If the values match, the update is allowed to proceed. If the values do not match, it means that another user has updated the record since you retrieved it, and your update will be rejected.

By using the [Timestamp] attribute, you can enable optimistic concurrency checks in your ASP.NET Core model classes and ensure that your data stays consistent even in a multi-user environment.

19- DefaultValue

The DefaultValue data annotation is used to specify a default value for a property.

20- NotMapped

The NotMapped data annotation is used to specify that a property should not be mapped to a database column.

Now let’s look at the Employee entity class and see that can we implement a significant number of data annotation for just one entity class.

Note: There are additional data annotations below that does not exist above.

Here is the Employee class:

In conclusion

Data annotations are a powerful feature of ASP.NET Core that can help you write cleaner, more efficient, and more secure code. By using these annotations to define validation rules, format strings, and other metadata for your model properties, you can simplify your code and make it easier to maintain. By understanding and using the 20 most important data annotations listed above, you can take full advantage of this feature and build better ASP.NET Core applications.

I appreciate your participation and hope that my article has provided you with valuable insights. Thank you for taking the time to read it thus far.

Onur Derman

Written by Onur Derman

Software Developer | C# | .Net Core | Javascript | linkedin.com/in/onrdrmn/

More from Onur Derman and Level Up Coding

10 Essential C# Libraries and Frameworks for Developers

10 Essential C# Libraries and Frameworks for Developers

C# is a powerful and versatile programming language, used in a variety of domains, such as web development, desktop applications, game….

Jacob Bennett

Jacob Bennett

The 5 paid subscriptions I actually use in 2024 as a software engineer

Tools i use that are cheaper than netflix.

5 Extremely Useful Plots For Data Scientists That You Never Knew Existed

Dr. Ashish Bamania

5 Extremely Useful Plots For Data Scientists That You Never Knew Existed

“5. theme river”.

Global Exception Handling in ASP.NET Core Web API: A Comparative Study of Two Approaches

Global Exception Handling in ASP.NET Core Web API: A Comparative Study of Two Approaches

When building a web application, error handling is an essential aspect of ensuring the application runs smoothly. one of the ways to…, recommended from medium.

Best Practices for Handling API Responses and Errors in ASP.NET and DotNet Core Web API

Anand Panchal

Best Practices for Handling API Responses and Errors in ASP.NET and DotNet Core Web API

Mastering api responses & errors in asp.net web api 🚀 learn best practices for delivering consistent and informative responses to clients..

Middleware vs. Exception Filters in ASP.NET Core: A Simplified Guide

Muhammad Abdullah

Middleware vs. Exception Filters in ASP.NET Core: A Simplified Guide

Imagine you’re at a bustling train station. middleware is like the security check at the entrance, ensuring everything is in order before….

what is data annotation in mvc

Predictive Modeling w/ Python

what is data annotation in mvc

data science and AI

Understanding When to Use Mappers vs. Manual Mapping in C#

Understanding When to Use Mappers vs. Manual Mapping in C#

Getting the Current User in Clean Architecture

Milan Jovanović

Getting the Current User in Clean Architecture

The applications you build serve your users (customers) to help them solve some problems. it’s a common requirement that you will need to….

Setup Entity Framework Core in Console Application, Code First

Robert Richardson

Setup Entity Framework Core in Console Application, Code First

Setting up entity framework core in a console application is pretty simple. in this tutorial i am going to show you how to setup entity….

C# Extension Methods that come in handy for an ASP.Net Project

Venky Writes

C# Extension Methods that come in handy for an ASP.Net Project

Extension methods serve as invaluable tools, empowering developers to enhance the expressiveness and efficiency of their code.

Text to speech

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Part 6: Using Data Annotations for Model Validation

  • 10 contributors

by Jon Galloway

The MVC Music Store is a tutorial application that introduces and explains step-by-step how to use ASP.NET MVC and Visual Studio for web development. The MVC Music Store is a lightweight sample store implementation which sells music albums online, and implements basic site administration, user sign-in, and shopping cart functionality. This tutorial series details all of the steps taken to build the ASP.NET MVC Music Store sample application. Part 6 covers Using Data Annotations for Model Validation.

We have a major issue with our Create and Edit forms: they're not doing any validation. We can do things like leave required fields blank or type letters in the Price field, and the first error we'll see is from the database.

We can easily add validation to our application by adding Data Annotations to our model classes. Data Annotations allow us to describe the rules we want applied to our model properties, and ASP.NET MVC will take care of enforcing them and displaying appropriate messages to our users.

Adding Validation to our Album Forms

We'll use the following Data Annotation attributes:

  • Required – Indicates that the property is a required field
  • DisplayName – Defines the text to use on form fields and validation messages
  • StringLength – Defines a maximum length for a string field
  • Range – Gives a maximum and minimum value for a numeric field
  • Bind – Lists fields to exclude or include when binding parameter or form values to model properties
  • ScaffoldColumn – Allows hiding fields from editor forms

*Note: For more information on Model Validation using Data Annotation attributes, see the MSDN documentation at * https://go.microsoft.com/fwlink/?LinkId=159063

Open the Album class and add the following using statements to the top.

Next, update the properties to add display and validation attributes as shown below.

While we're there, we've also changed the Genre and Artist to virtual properties. This allows Entity Framework to lazy-load them as necessary.

After having added these attributes to our Album model, our Create and Edit screen immediately begin validating fields and using the Display Names we've chosen (e.g. Album Art Url instead of AlbumArtUrl). Run the application and browse to /StoreManager/Create.

Screenshot of the Create form showing the Genre and Artist dropdowns and the Title, Price, and Album Art U R L fields.

Next, we'll break some validation rules. Enter a price of 0 and leave the Title blank. When we click on the Create button, we will see the form displayed with validation error messages showing which fields did not meet the validation rules we have defined.

Screenshot of the Create form showing the Title and Price fields in red due to errors in input and accompanying red error.

Testing the Client-Side Validation

Server-side validation is very important from an application perspective, because users can circumvent client-side validation. However, webpage forms which only implement server-side validation exhibit three significant problems.

  • The user has to wait for the form to be posted, validated on the server, and for the response to be sent to their browser.
  • The user doesn't get immediate feedback when they correct a field so that it now passes the validation rules.
  • We are wasting server resources to perform validation logic instead of leveraging the user's browser.

Fortunately, the ASP.NET MVC 3 scaffold templates have client-side validation built in, requiring no additional work whatsoever.

Typing a single letter in the Title field satisfies the validation requirements, so the validation message is immediately removed.

Screenshot of the Create form showing the Price field in red due to an error in input and accompanying red error text.

Previous Next

Was this page helpful?

Submit and view feedback for

Additional resources

  • 90% Refund @Courses
  • Trending Now
  • Data Structures & Algorithms
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Web Development
  • Web Browser

Related Articles

  • DSA to Development
  • Java ActionListener in AWT
  • JSTL Core <c:param> Tag
  • HandlerAdapters in Spring MVC
  • Installing Spring Tool Suite on Windows
  • How to Create Servlet in MyEclipse IDE?
  • Spring Boot - Interceptor
  • JUnit 5 @BeforeAll Annotation with Examples
  • JSTL Core <c:out> Tag
  • Working With HTTP Headers in Spring MVC: A Guide to @RequestHeader and @ResponseHeader
  • JSTL Core <c:url> Tag
  • Struts 2 Features
  • Top 10 Most Used Spring Boot Annotations
  • Spring Boot - Internationalization
  • MBR v/s GPT Partition in OS
  • Spring Batch - Job Scheduling and Job Execution
  • What is Spring Modulith?
  • SpringBoot Configuration
  • JUnit 5 – @Disabled
  • Implementation of Spring Cloud Netflix - Eureka

Top 10 Spring MVC Annotations with Examples

In the world of Spring MVC , annotations are like a reliable assistant for your web applications. They usually work behind the scenes of your application and make tasks easier. Also, they help the developers to communicate clearly with their applications and ensure what the developers actually want to do with their applications.

Spring MVC Annotations with Examples

In this article, we will have a closer look at the Top 10 Spring MVC annotations , each one having its own role. Once you’re familiar with them, you’ll be able to use Spring MVC more confidently and you can create web applications that are both efficient as well as user-friendly.

What are Spring MVC Annotations?

Imagine you’re building a website or web application and you want to make sure that it works smoothly and does what you want it to do. Spring MVC is like a set of tools that helps you build these web applications using Java Programming Language . Now, think of annotations as special notes or instructions that you attach to your code. These notes tell Spring MVC how different parts of your code should work together. They’re like little tags that help Spring MVC understand your code better and make it easier for you to build your web applications.

For more details about Spring Annotations, Follow Spring Annotations .

Top 10 Spring MVC Annotations

Now that we have understood the basics of Spring MVC annotations, let’s learn about the Top 10 Spring MVC annotations with code examples. Here we will be learning about every annotation in detail with examples of source code.

1. @ RequestMapping

The @RequestMapping annotation is a class-level annotation. It is used to map HTTP requests to their respective methods. The request mapping annotation is a generic one. This means that it can be used regardless of the request being GET, POST, PUT, DELETE, or PATCH . You can think of the request mapping as an index page. You visit the index page of your book, look up the topic you want to read, and then jump to the particular page number that contains this topic. Similarly, the requests come to this annotation, look up where the method they want to go is, and jump to that method without getting lost. Let us understand the request mapping annotation with a small example.

Class Level Annotation: Annotations that can be applied only to classes.

Method Level Annotations: Annotations that can be applied to methods only.

What is happening in the code above? When the user visits “…/api/v1/geeks/getMessage”, then the request stops at the request mapping annotation. It then looks for the method that should be executed for Uri “/getMessage”. Upon successfully identifying the request, the getMessage method returns “GeeksForGeeks” to the user on the browser page.

2 . @ Controller

The @Controller annotation is a specialized form of @Component annotation. It is a class level annotation. It simply allows for classes marked as @Configuration to be auto detected by the spring application context. Without the @Controller annotation, you would get an error claiming that no beans were found for the respective class. Let us understand the controller annotation with an example.

What is happening in the code above? In the above code, the client class wants to use an object called RestTemplate. Since, the spring framework has already defined an implementation for this object, we want to be able to use the same in our code. In order to do so, we need to tell the spring framework that “I want to use this class, please generate it’s object at runtime” and to do this we use the @Controller annotation in our client class.

Meanwhile, in the server class, we tell the spring framework that “I will be writing certain methods in this class, that define the objects that I need in my code at runtime”. To achieve this, we use @Configuration annotation. And, we apply the @Bean annotation at the level of the methods to return these particular objects. Thus, a proper “handshake” between @Configuration for server class and @Controller for client class, helps us to achieve the OOP principle of “abstraction” in our code.

3. @ ResponseBody

The @ResponseBody annotation can be applied to classes as well as methods. This annotation has to do with what is being sent back to the user as an output. It is used for automatic serialization of the output by a method in the controller layer. Consider the Java Code below that makes use of this annotation:

Now, the application is started and the user hits the respective URIs “…/gfg/geek1” and “…/gfg/geek1/number”.

The method returns the string and the integer in the respective cases. But because we have used the ResponseBody annotation, before returning to the user, this automatically is converted to a JSON.

Thus the output of the Response body annotation will be some serializable format like JSON or XML.

4. @ RestController

This annotation is simply the combination of @Controller and @ResponseBody annotation. With the @RestController annotation, you no longer need to annotate each and every method with @ResponseBody. Mind you, do not use this annotation when you are rendering pages for example: in thymeleaf. You don’t want to serialize your html code! Let us Understand how this works with code examples from the previous section:

5. @ RequestParam

The @RequestParam annotation can be used to assign variables to query parameters in Http Requests. Suppose that we want to access a URL with one or more query parameters in it. The URL we visit is: http://localhost:8080/api/v1/geeks?firstname=John&lastname=doe

Now, we want to extract firstname and lastname from this URL. This is where the @RequestParam URL comes in. Let us understand with a code sample:

If we have only one query parameter then mentioning the name of the parameter is totally optional. For eg: If we were passing just the firstname then we could have written: public void demo(@RequestParam String fname).

6. @ PathVariable

To understand @PathVariable, let us first look at what are template variables in a URI. Suppose we have an http request as: http://localhost:8080/index/page1 when the user want to view page1. Similarly there are n other pages that can be viewed. The URL for these pages is similar to that of page1 …/index/page2 to ../index/pageN. Now, to generalize what page we want to load based on user’s choice, we can use template variables. Using template variables, we can write the URL as http://localhost:8080/index/{page} where page is variables that has values as page=page1, page2, page3…pageN. Thus {page} here is referred to as a template variable.

At the backend, we can extract these variables from the URL and use them to serve the respective pages. This is where the @PathVariables annotation comes in. It helps us to extract template variables from http URLs and assign them to variables in our code. Let us understand this with the help of a code.

Now, if the mapping is /index/page1 User would see the message You visited page1 on their browser window. Similarly for any other pages.

7. @ RequestBody

Just like @RequestParam extracts query parameters and the @RequestBody extracts template variables from http URL requests, the @RequestBody annotation helps us to read the data in the body of the http request and allows it’s process by binding it to variables, Maps or POJOs.

Generally, when we know what kind of data is returned from the http body, we can use variables and POJOs. But, incase we have a doubt as to what is being returned with the body, we can use Maps.

Let us see how this works with a code example.

Now suppose we send the following JSON as request body with our Http Request.

We could have written any number of key-value pairs in request body, and it would mapped to a Map with the respective key-value pairs. In this we simply get the output message as: The name of the user is= Geek and their id is= 3. This is how the @RequestBody annotation works. For more details, read here .

8. @ CookieValue

The @CookieValue annotation is used to tie the value of http cookies to the method arguments of controllers in Spring MVC. For eg:

On running the above snippet, we can view the JSESSIONID of the current user on the console.

9. @ CrossOrigin

The @CrossOrigin is very imported in Spring. If you have a spring backend and a a JavaScript frontend in react, angular or vue and on trying to communicate with the backend you receive a CORS error, then it is likely that you have not used the @CrossOrigin annotation. This annotation is extremely important because it defines what all ports on your computer can communicate with the backend. CORS stands for Cross Origin Resource Sharing. This annotation can be used on the method level or the class level.

In the above controller method getMessage, we explicitly allow the traffic from localhost:3000(for react frontends) to enter our backend server.

10. @ ExceptionHandler

This annotation is used to handle the exceptions in controller classes. Should any exceptions occur, the @ExceptionHandler annotation is used to catch these exceptions and display messages to the users accordingly. The @ExceptionHandler is also called as a Local Exception Handler in spring, because it handles exceptions at the class level.

In the above code example, if on executing any of the controller methods we get the ArrayIndexOutOfBoundsException then the getErrorMessage2() method is executed. For the NullPointerException, the first method is executed. We can add as many @ExceptionHandlers as we want. They help us to convey to the client why the system is running into errors.

In this article, we have learned about the top 10 Spring MVC annotations and their uses for creating robust web applications. When you know these annotations inside out, you can keep your code neat, handle requests smoothly, and make error messages friendlier for users. Understanding these annotations really well is a key part of becoming great at Spring MVC. ​

Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Please Login to comment...

author

  • Geeks Premier League 2023
  • Advance Java
  • Geeks Premier League

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Data Annotation in MVC Application

    what is data annotation in mvc

  2. Data Annotation Validation with Example in ASP.NET MVC

    what is data annotation in mvc

  3. Data Annotation

    what is data annotation in mvc

  4. Range Data Annotation Attribute in MVC

    what is data annotation in mvc

  5. Data Annotation Attributes in ASP.NET MVC

    what is data annotation in mvc

  6. Data Annotations and Validations in MVC 5

    what is data annotation in mvc

VIDEO

  1. Data Annotation with Client & Server Side Custom Validation in MVC 5

  2. ASP.NET MVC Tutorial #7

  3. Custom Data Annotation 1

  4. How Validation works in MVC? What is data Annotation ?

  5. Spring MVC Tutorials 15

  6. Custom Data Annotations or Custom Validation Attributes in MVC

COMMENTS

  1. Data Annotations in ASP.NET Core MVC

    Advantages of Data Annotations: Simplicity: Data annotations are easy to use and understand. You can set its behavior by simply adding an attribute above a property. Centralized Configuration: Data annotations allow for co-locating validation, display, and data modeling configurations with the properties themselves, leading to centralized, at-a-glance configuration.

  2. Data Annotations And Validation In MVC

    Predefined data annotation validation in MVC; Custom defend data annotation validation in MVC. In this article, we will discuss all the predefined data annotation validation listed in System.ComponentModel.DataAnnotations namespace. Prerequisite For easy understanding of this article, you should have minimal ASP.Net MVC knowledge. At least, you ...

  3. A Complete Guide to Data Annotations in .NET MVC

    In this blog post, we'll explore all the data annotations available in .NET MVC, with examples and best practices for using them effectively. Whether you're a beginner or an experienced .NET MVC developer, you'll learn how to create more secure and reliable applications with data annotations. Required Attribute:

  4. Data Annotation In ASP.NET MVC

    Data annotation attributes are attached to the properties of the model class and enforce some validation criteria. They are capable of performing validation on the server side as well as on the client side. This article discusses the basics of using these attributes in an ASP.NET MVC application. Create an empty MVC Project. Add two models as " ".

  5. ASP.NET MVC

    DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of .NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations.

  6. Data Annotation Attributes in ASP.NET MVC

    In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.

  7. Model Validation Using Data Annotations In ASP.NET MVC

    Data Annotations are nothing but certain validations that we put in our models to validate the input from the user. ASP.NET MVC provides a unique feature in which we can validate the models using the Data Annotation attribute. Import the following namespace to use data annotations in the application. System.ComponentModel.DataAnnotations

  8. MVC Data Annotations for Model Validation

    MVC Data Annotations for Model Validation Server Side Model Validation in MVC Razor Different ways of rendering layouts in Asp.Net MVC Inline CSS and Styles with Html Helpers in MVC3 Razor

  9. Data Validation in ASP.NET MVC

    These attributes are used to define metadata for ASP.NET MVC and ASP.NET data controls. You can apply these attributes to the properties of the model class to display appropriate validation messages to the users. The following table lists all the data annotation attributes which can be used for validation. Attribute. Usage.

  10. Model validation in ASP.NET Core MVC

    This article explains how to validate user input in an ASP.NET Core MVC or Razor Pages app. View or download sample code ( how to download ). Model state Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors.

  11. System.ComponentModel.DataAnnotations Namespace

    Data Annotations Namespace Reference Feedback In this article Classes Interfaces Enums Provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls. Classes Expand table Interfaces Expand table IValidatable Object Provides a way for an object to be validated. Enums Expand table Data Type

  12. c#

    How do Data Annotations work? Ask Question Asked 12 years, 7 months ago Modified 6 years, 2 months ago Viewed 36k times 24 I use Data Annotations in my ASP.NET MVC 3 project to validate the model. These are extremely convenient but currently they are magic to me. I read that data annotations do not throw exceptions.

  13. Data Annotation Attributes in ASP.NET Core MVC

    Compare Data Annotation Attribute in ASP.NET MVC Application: Compare Attribute in ASP.NET Core MVC Framework is used to compare 2 model properties with the same value. Comparing credit card numbers and passwords is the common use case of the Compare attribute. Let's understand using the Compare attribute with an example.

  14. Data annotation in ASP.NET MVC (Example with creating Custom Validation)

    Data Annotations is a namespace, providing attribute classes, which are used to define metadata for controls. Data Annotations allow us to describe the rules we want to be applied to our model properties, and ASP.NET MVC will take care of enforcing them and displaying appropriate messages to our users. MVC Provides a large number of Data ...

  15. Validation with the Data Annotation Validators (C#)

    In order to use the Data Annotations Model Binder in an ASP.NET MVC application, you first need to add a reference to the Microsoft.Web.Mvc.DataAnnotations.dll assembly and the System.ComponentModel.DataAnnotations.dll assembly. Select the menu option Project, Add Reference.

  16. 20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data

    7- DataType. The DataType data annotation is used to specify the data type of a property. public class Employee {[DataType(DataType.DateTime)] public DateTime DateOfBirth { get; set; }}. In this example I used DataType.DateTime but there are other data types that can be specified using the [DataType] attribute in ASP.NET Core.

  17. Part 6: Using Data Annotations for Model Validation

    Adding Validation to our Album Forms. We'll use the following Data Annotation attributes: Required - Indicates that the property is a required field. DisplayName - Defines the text to use on form fields and validation messages. StringLength - Defines a maximum length for a string field. Range - Gives a maximum and minimum value for a ...

  18. Top 10 Spring MVC Annotations with Examples

    Here we will be learning about every annotation in detail with examples of source code. 1. @RequestMapping. The @RequestMapping annotation is a class-level annotation. It is used to map HTTP requests to their respective methods. The request mapping annotation is a generic one.

  19. Using ASP.Net MVC Data Annotation outside of MVC

    Using ASP.Net MVC Data Annotation outside of MVC Ask Question Asked 13 years, 7 months ago Modified 3 years, 9 months ago Viewed 9k times 23 i was wondering if there is a way to use ASP.Net's Data annotation without the MVC site. My example is that i have a class that once created needs to be validated, or will throw an error.

  20. spring mvc

    Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams