ASP.NET Core MVC Beginner

Model validation

Validation makes sure data is correct before you use it. ASP.NET Core MVC checks rules you declare with attributes, records the results in ModelState, and can also validate in the browser. This lesson covers the common attributes, checking ModelState and showing errors.

Validation from submit to response
  1. StartForm is postedThe browser sends the fields
  2. Step 2Model bindingFields are copied into the model
  3. Step 3Rules are checked[Required], [StringLength], [Range], [EmailAddress]...
  4. Step 4Errors go to ModelStateEach failed rule adds a message for its property
  5. EndAction checks IsValidInvalid: return View(model) with messages. Valid: save and redirect

The idea in plain words

You describe the rules once on your model with attributes. After model binding, MVC runs those rules automatically and stores any errors in ModelState. Your action only needs to check ModelState.IsValid and decide what to do.

The same attributes also drive client-side validation in the browser through the jQuery Validation scripts in the template. Client validation is a convenience for users; server validation is what keeps your data safe, because anyone can bypass the browser.

Example: rules on a model

When nullable reference types are enabled, a non-nullable string property is treated as required even without [Required].

C#
public class SignUpModel
{
    [Required, StringLength(50)]
    public string Name { get; set; } = "";

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

    [Range(18, 120, ErrorMessage = "You must be at least 18.")]
    public int Age { get; set; }

    [DataType(DataType.Password), MinLength(8)]
    public string Password { get; set; } = "";

    [Compare(nameof(Password), ErrorMessage = "Passwords do not match.")]
    public string ConfirmPassword { get; set; } = "";
}

Example: checking and adding errors

Rules that need a database or another service, such as checking that an email is free, go in the action or a service. Add your own messages with ModelState.AddModelError.

C#
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SignUp(SignUpModel model)
{
    if (await _users.EmailExistsAsync(model.Email))
        ModelState.AddModelError(nameof(model.Email), "This email is already registered.");

    if (!ModelState.IsValid)
        return View(model); // the form shows the messages

    await _users.CreateAsync(model);
    return RedirectToAction("Welcome");
}

Common mistakes

  • Relying only on client-side validation.
  • Forgetting to return the view with the same model, so the user loses what they typed.
  • Not adding _ValidationScriptsPartial to the Scripts section, so browser validation does not run.
  • Putting database checks inside validation attributes instead of the action or a service.

Interview question

Why do you need server-side validation if client-side validation already works?

Client-side validation runs in the browser and can be disabled or bypassed by anyone sending requests directly, for example with a script or a tool like curl. Server-side validation in ASP.NET Core runs on every request after model binding, so it is the only check you can trust. Client validation just gives faster feedback to users.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.