Data annotations are a set of attributes that can be applied to model properties in ASP.NET applications to specify validation rules, formatting, and display information. They provide a simple way to enforce validation rules on user input and can be used to enhance the user experience by providing immediate feedback on data entry.

Common Data Annotations

Here are some commonly used data annotation attributes for validation:

  • [Required]: Specifies that a property must have a value.
  • [StringLength]: Specifies the maximum length of a string property.
  • [Range]: Specifies the minimum and maximum values for a numeric property.
  • [EmailAddress]: Validates that a property contains a valid email address.
  • [RegularExpression]: Validates that a property matches a specified regular expression.

Using Data Annotations for Validation

To use data annotations for validation in ASP.NET Web Pages, you typically follow these steps:

  1. Create a model class with properties decorated with data annotation attributes.
  2. Use the model in your Razor page to bind form data.
  3. Validate the model on form submission and display validation messages as needed.

Step 1: Create a Model Class

Here’s an example of a simple model class for user registration that uses data annotations for validation:

        
using System.ComponentModel.DataAnnotations;

public class UserRegistration
{
[Required(ErrorMessage = "Username is required.")]
[StringLength(50, ErrorMessage = "Username cannot be longer than 50 characters.")]
public string Username { get; set; }

[Required(ErrorMessage = "Password is required.")]
[StringLength(100, MinimumLength = 6, ErrorMessage = "Password must be at least 6 characters long.")]
public string Password { get; set; }

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

Step 2: Create a Razor Page for the Form

In your Razor page, you can create a form that binds to the model and uses data annotations for validation:

        
@using YourNamespace // Replace with the actual namespace of your model
@{
var user = new UserRegistration();
var errorMessage = "";
if (IsPost)
{
// Validate the model
var context = new ValidationContext(user, null, null);
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(user, context, results, true);

if (!isValid)
{
errorMessage = string.Join("<br />", results.Select(r => r.ErrorMessage));
}
else
{
// Process the data (e.g., save to database)
<p>Registration successful for @user.Username!</p>
}
}
}
@if (!string.IsNullOrEmpty(errorMessage))
{
<p style="color:red;">@Html.Raw(errorMessage)</p>
}
<h2>Registration Form</h2>
<form method="post" action="/register">
<label for="username">Username:</label>
<input type="text" name="Username" id="username" required placeholder="Enter your username" value="@user.Username" />

<label for="password">Password:</label>
<input type="password" name="Password" id="password" required placeholder="Enter your password" value="@user.Password" />

<label for="email">Email:</label>
<input type="email" name="Email" id="email" required placeholder="Enter your email" value="@user.Email" />

<button type="submit">Register</button>
</form>

Conclusion

Data annotations provide a powerful and convenient way to implement validation in ASP.NET Web Pages. By decorating model properties with attributes like [Required], [StringLength], and [EmailAddress], you can enforce validation rules that enhance data integrity and user experience. When combined with Razor pages, data annotations allow for seamless validation and error messaging, ensuring that users receive immediate feedback on their input. This approach not only simplifies the validation process but also keeps your code clean and maintainable, making it easier to manage user input across your application.