A Basic Guide on Data Annotations in Asp.Net MVC

Data annotations are used to make configurations on your model classes that highlights the most common settings required. The AnnotationsData is also understood by a number of .NET apps, such as ASP.NET MVC, that allow these apps to take advantage of the same annotations for client-side validations. The Data Annotation attributes supersede the default Code-First conventions.

Why do we require data annotation attributes on ASP.NET MVC?

Now one day it is a difficult job for a web developer to validate the user’s contribution to any web application. As a web developer, we are not satisfied with validating the business logic on the client-side of the browser. However, we also need to validate the business logic that runs on the Server. This means, as a developer, we have to validate the business logic on both the client and server sides.

Customer-side validation of business logic provides users with instant feedback on the information they have entered for a webpage and that is the feature expected in today’s web applications. In the same way, server-side validation logic is in place because we never trust information coming from the Internet

What are the Validations?

In simple terms, we can say that validations are only a few rules set by the developer on the entry fields of a webpage in order to satisfy the management rules for this particular entry field must maintain the appropriate data within a system.  Validation can be divided into two types:

  1. Validation on the Server-side
  2. Validation on the client-side.

During validations, as a developer, we have to take care not only of the appropriate validation but also ensure that the validation follows the business rule in accordance with the requirement. From a security perspective, some hackers may also be able to bypass client-side validation and insert some vulnerable data onto the server.

In ASP.NET MVC web applications, we can carry out the following three types of validation:

  1. HTML validations / JavaScript validations (i.e. Client-Side Validation)
  2. Validation of the MVC ASP.NET model (i.e. Server-side Validation)
  3. Validating the database (i.e. Server-side Validation)

Among those three elements, the most secure validation is the validation of the ASP.NET MVC model. In HTML/JavaScript validation, validation may break easily by disabling javascript in the client machine, but model validation may not break.

ASP.NET MVC Framework provides a concept called Data Overlay that is used for model validation. It is a legacy of the System.ComponentModel.DataAnnotations assembly.

This means that ASP.NET MVC Framework uses data annotation attributes to implement model validation. Data annotation attributes include integrated validation attributes for Different validation rules that can be applied to the properties of model classes.

The ASP.NET MVC box automatically applies the validation rules and is displayed appropriate validation messages on the view in the event of validation failure.

The data annotation may be used after the addition of the following namespace.

System.ComponentModel.DataAnnotations

using System.ComponentModel;

DATA ANNOTATION ATTRIBUTES.

Here you can find a list of certain important data annotation attributes.

1. Required

Specifies that the Entry field cannot be blank.

Example:

[Required(ErrorMessage = “Name is Required”)]

public string Name { get; set; }

2. DisplayName

Defines the display name of a property.

Example:

[DisplayName(“Enter Your Name: “)]

public string Name { get; set; }

3. StringLength

Specifies the minimum and maximum length of ownership.

Example:

[StringLength(50, MinimumLength = 3)]

public string Name { get; set; }

4. Range

Specifies an array of numerical values.

Example:

[Range(1,120, ErrorMessage =”Age should range from 1 to 120 years.”]

public int Age { get; set; }

5. Bind

Incorporate or exclude a value when adding form values to model properties.

Example:

[Bind(Exclude = “Id”)]

6. ScaffoldColumn

Specifies a field to hide from publisher forms.

Example:

[ScaffoldColumn(false)]

public int Id { get; set; }

7. DisplayFormat

Specifies a display format for a property such as date format, currency format, and so on.

Example:

[DisplayFormat(DataFormatString = “{0:dd/MM/yyyy hh:mm:ss tt}”)]

public System.DateTime? HireDate { get; set; }

8. ReadOnly

It defines a read-only property.

Example:

[ReadOnly(true)]

public string FullName{ get; private set; }

9. MaxLength

Defines the maximum length of the chain.

Example:

[MaxLength(50)]

public string Name { get; set; }

10. CreditCard

indicates that a data field is associated with the credit card number.

Example:

[DataType(DataType.CreditCard)]

public string Name { get; set; }

11. Compare

comparison with other input fields.

Example:

[System.ComponentModel.DataAnnotations.Compare(“Email”, ErrorMessage=”Email Not Matched”)]

public string ConfirmEmail { get; set; }

12. EmailAddress

specifies that an entry field value is a well-formed e-mail address using the regular expression.

Example:

[Required(ErrorMessage = “Email ID is Required”)]

[DataType(DataType.EmailAddress)]

[MaxLength(50)]

[RegularExpression(@ “[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}”, ErrorMessage = “Incorrect Email Format”)]

public string Email { get; set;}

13. Phone

specifies that a value of the input field is a well-formed telephone number using the regular expression.

Example:

[DataType(DataType.PhoneNumber)]

[RegularExpression(@”^\(?([0-9]{2})[-. ]?([0-9]{4})[-. ]?([0-9]{3})[-. ]?([0-9]{3})$”, ErrorMessage = “Not a valid Phone number”)]

public string Name { get; set; }

Output format: 91-1234-567-890

14. Url

specifies the validations of the URL.

Example:

[Url][Required]

public string URL { get; set; }

15. RegularExpression

specifies that the input field matches the regular expression you want.

Example:

[RegularExpression(@”[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}”, ErrorMessage = “Incorrect Email Format”)]

public string Email { get; set; }

16. DataType

provides a list of the data type associated with the entry field and parameter.

Example:

[DataType(DataType.EmailAddress)]

public string Email { get; set; }

17. HiddenInput

specifies an entry field that is hidden.

Example:

[System.Web.Mvc.HiddenInput(DisplayValue = false)]

public string Name { get; set; }

We have a major problem with our creation and modification forms: they make no validation. We can do things such as leaving the required fields blank or typing letters in the Price field, and the first error we’ll see is in the database.

Conclusion

We are familiar with the data annotation embedded in the ASP.Net MVC framework.

Data annotation attributes apply directly to members of the Model class and these members are limited to accepting valid user entries following the data annotation rule. When we speak of validation in the ASP.NET MVC framework, we focus mainly on the validation of the value of the model. In other words, did the user provide any value requirements? Is the value within the requested range? Is the value in an appropriate size?

Leave a Comment