MVC-Validation


In ASP.NET MVC, validation is crucial for ensuring that the data submitted by users is correct and meets the expected criteria. There are several ways to handle validation in MVC, but one of the most commonly used methods is through Data Annotations.

MVC validation

Data Annotations

Data Annotations are attributes you can apply to model properties to specify validation rules and display information. These attributes are part of the System.ComponentModel.DataAnnotations namespace and are used to enforce validation on the server side and, with the help of JavaScript libraries, on the client side as well.

Common Data Annotations

Here are some of the commonly used Data Annotations:

  • [Required] - Ensures that the property must have a value.

  • [StringLength] - Sets the maximum and optionally the minimum length of a string property.

  • [Range] - Specifies the minimum and maximum value for a numeric property.

  • [RegularExpression] - Validates the property value with a regular expression.

  • [EmailAddress] - Validates that the property is a valid email address.

  • [Compare] - Compares two properties to see if they match (useful for password confirmation fields).

Example

using System.ComponentModel.DataAnnotations;

public class UserModel
{
    [Required(ErrorMessage = "Name is required")]
    [StringLength(100, ErrorMessage = "Name cannot be longer than 100 characters")]
    public string Name { get; set; }

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

    [Required(ErrorMessage = "Age is required")]
    [Range(1, 100, ErrorMessage = "Age must be between 1 and 100")]
    public int Age { get; set; }

    [Required(ErrorMessage = "Password is required")]
    public string Password { get; set; }

    [Compare("Password", ErrorMessage = "Password and Confirmation Password must match")]
    public string ConfirmPassword { get; set; }
}

How Validation Works

  1. Model Binding - When a form is submitted, MVC binds the form data to the model properties.

  2. Validation - The framework automatically performs validation based on the Data Annotations applied to the model properties.

  3. Validation Results - If validation fails, MVC adds error messages to the ModelState object, which can be accessed in the controller to determine if the model is valid.

  4. Client-Side Validation - Using JavaScript libraries like jQuery Validation, you can also enforce validation rules on the client side, providing immediate feedback to users.

Example in Controller

public ActionResult Register(UserModel model)
{
    if (ModelState.IsValid)
    {
        // Save data to the database or perform other actions
        return RedirectToAction("Success");
    }
    // If validation fails, return the same view with validation messages
    return View(model);
}

Next