You are currently viewing ASP.NET Core Model Validation Finally Made Sense to Me: Data Annotations and ModelState

ASP.NET Core Model Validation Finally Made Sense to Me: Data Annotations and ModelState

When I first started working with forms in ASP.NET Core MVC, validation looked simple.

You add [Required] to a property, ASP.NET somehow knows the field is required, and an error message magically appears on the screen.

Okay…but how does all of that actually connect?

That was the part I wanted to understand.

Once I looked at validation as part of the MVC flow instead of just memorizing attributes, it started making much more sense.

The basic flow looks like this:

User fills out a form
        ↓
View sends the form
        ↓
Controller receives the data
        ↓
ASP.NET Core checks validation rules
        ↓
ModelState.IsValid
       / \
    true   false
     ↓       ↓
 Process   Return View
  data     with errors

That little ModelState.IsValid line is doing a lot more work than it looks like.

Let’s break it down.


What Is Model Validation?

Model validation simply means:

Checking whether the data submitted by the user follows the rules of the application.

For example, imagine a form for creating a financial account.

We might ask the user for:

  • Account name
  • Account type
  • Starting balance

We probably don’t want someone submitting a blank account name.

We might also want to limit how long the account name can be.

Those are validation rules.

In ASP.NET Core MVC, we can place many of those rules directly on properties in a ViewModel.

For example:

using System.ComponentModel.DataAnnotations;

public class CreateAccountViewModel
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; } = string.Empty;

    [Required]
    public string AccountType { get; set; } = string.Empty;

    [Range(0, 10000000)]
    public decimal StartingBalance { get; set; }
}

The attributes above the properties are called Data Annotations.

They tell ASP.NET Core how the data should be validated.


What Does [Required] Do?

This one is pretty easy to understand.

[Required]
public string Name { get; set; }

It means the user must provide a value.

If the user submits the form without entering a name, ASP.NET Core will add a validation error.

We can also create our own message:

[Required(ErrorMessage = "Please enter an account name.")]
public string Name { get; set; } = string.Empty;

Now the user gets a friendlier message instead of a generic validation message.

I prefer messages that actually tell the user what to fix.


What Does [StringLength] Do?

Suppose I don’t want an account name with 600 characters.

I can limit it:

[StringLength(100)]
public string Name { get; set; } = string.Empty;

Now the maximum length is 100 characters.

We can also set a minimum:

[StringLength(100, MinimumLength = 2)]
public string Name { get; set; } = string.Empty;

That means the value must contain at least 2 characters and no more than 100.


What Does [Range] Do?

[Range] works well for numbers.

For example:

[Range(0, 10000000)]
public decimal StartingBalance { get; set; }

This means the starting balance must be between:

0
and
10,000,000

If the user enters a number outside that range, validation fails.

You could also use it for something like quantity:

[Range(1, 100)]
public int Quantity { get; set; }

Now zero isn’t allowed.

Neither is 500.


So Who Actually Checks These Rules?

This was the part I wanted to understand.

ASP.NET Core does the checking during model binding.

Here’s the simplified flow:

HTML Form

Name = "Checking"
AccountType = "Bank"
StartingBalance = 500

        ↓

HTTP POST Request

        ↓

ASP.NET Core Model Binding

        ↓

CreateAccountViewModel

Name = "Checking"
AccountType = "Bank"
StartingBalance = 500

        ↓

Validation Rules Checked

        ↓

ModelState

ASP.NET Core takes the form values and tries to build the object that your controller expects.

For example:

[HttpPost]
public IActionResult Create(CreateAccountViewModel model)
{
}

ASP.NET Core sees:

CreateAccountViewModel model

and basically says:

Okay. I need to build one of these objects using the values that came from the form.

Then it checks the Data Annotation rules.

The results are stored in something called ModelState.


What Is ModelState.IsValid?

This is the line you will see all over ASP.NET Core MVC applications:

if (!ModelState.IsValid)
{
    return View(model);
}

In plain English, I read this as:

If something is wrong with the submitted data, don’t continue. Send the user back to the form.

That’s it.

You could mentally translate this:

if (!ModelState.IsValid)

into:

IF THE FORM HAS ERRORS

And this:

return View(model);

means:

SHOW THE FORM AGAIN

So the whole thing becomes:

IF THE FORM HAS ERRORS
    SHOW THE FORM AGAIN

That is much easier for me to remember than trying to make ModelState sound more complicated than it is.


A Simple Controller Example

Here is a basic controller action:

[HttpPost]
public IActionResult Create(CreateAccountViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // Save the account

    return RedirectToAction("Index");
}

The flow looks like this:

POST Create
     ↓
Receive ViewModel
     ↓
Is ModelState valid?
     ↓
 ┌───────────────┐
 │               │
No              Yes
 │               │
 ↓               ↓
Return View     Save data
with errors      ↓
                Redirect

There is an important idea here.

The controller does not immediately save the data.

It checks whether the submitted information is valid first.


Showing Validation Errors in the View

Now we need the View to display those errors.

A Razor form might look like this:

<form asp-action="Create" method="post">

    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
        <span asp-validation-for="Name"></span>
    </div>

    <div>
        <label asp-for="AccountType"></label>
        <input asp-for="AccountType" />
        <span asp-validation-for="AccountType"></span>
    </div>

    <button type="submit">Create Account</button>

</form>

Notice this line:

<span asp-validation-for="Name"></span>

That is where the validation message can appear.

For example:

Account Name
[                  ]

Please enter an account name.

The ViewModel contains the rule.

[Required(ErrorMessage = "Please enter an account name.")]
public string Name { get; set; }

The controller checks ModelState.

if (!ModelState.IsValid)
{
    return View(model);
}

And the View knows where to display the error.

<span asp-validation-for="Name"></span>

Now the pieces connect.


View → ViewModel → Controller

This is where validation fits into the MVC flow I have been learning.

           USER
             ↓
            VIEW
             ↓
         VIEWMODEL
             ↓
         CONTROLLER
             ↓
     ModelState.IsValid
          /       \
       FALSE       TRUE
         ↓           ↓
       VIEW      BUSINESS LOGIC
                         ↓
                     DATABASE

The View collects the data.

The ViewModel describes the data the View needs and contains validation rules.

The Controller receives the ViewModel.

ASP.NET Core validates it.

Then the Controller decides what happens next.

That is the big picture.


Why Validate a ViewModel Instead of the Database Entity?

This is another reason I like using ViewModels for forms.

Imagine our database entity looks like this:

public class Account
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public decimal Balance { get; set; }

    public DateTime CreatedDate { get; set; }

    public int UserId { get; set; }
}

But the Create Account form only needs:

Name
Account Type
Starting Balance

The user should not be entering things like:

Id
CreatedDate
UserId

Those values should normally be controlled by the application.

So instead of sending the entire database entity through the form, we can create a ViewModel designed specifically for that screen.

public class CreateAccountViewModel
{
    [Required]
    public string Name { get; set; } = string.Empty;

    [Required]
    public string AccountType { get; set; } = string.Empty;

    [Range(0, 10000000)]
    public decimal StartingBalance { get; set; }
}

That creates a cleaner separation:

DATABASE ENTITY
What the database needs

        ≠

VIEWMODEL
What the screen needs

They may contain some of the same fields, but they have different jobs.


Server-Side Validation vs Client-Side Validation

ASP.NET Core can also display validation errors in the browser before the form reaches the server.

That is called client-side validation.

For example:

User leaves Name blank
        ↓
Browser displays error
        ↓
User fixes it

That’s great for the user experience.

But server-side validation is still important.

You should never depend only on the browser.

Someone could send a request directly to your application without using your form at all.

So I think about the two types like this:

CLIENT-SIDE VALIDATION
"Help the user catch mistakes quickly."

SERVER-SIDE VALIDATION
"Protect the application from bad input."

Both have a purpose.


Can the Controller Add Its Own Validation Error?

Yes.

Not every rule fits nicely into [Required], [Range], or another attribute.

Sometimes the controller or business logic discovers a problem.

For example, maybe an account with the same name already exists.

We can manually add an error:

ModelState.AddModelError(
    "Name",
    "An account with this name already exists."
);

Then check the ModelState again:

if (!ModelState.IsValid)
{
    return View(model);
}

The View can display that error just like the errors created by Data Annotations.


What I Would Remember for a Job Interview

If someone asked me:

“How does model validation work in ASP.NET Core MVC?”

I would explain it like this:

ASP.NET Core uses model binding to create an object from submitted form data. Validation rules such as Data Annotations are checked, and the results are stored in ModelState. The controller can check ModelState.IsValid before processing or saving the data. If validation fails, the controller normally returns the View with the submitted model so the user can correct the errors.

That answer shows more understanding than simply saying:

“I use [Required].”

Because [Required] is only one small piece of the process.

The real flow is:

Form
 ↓
Model Binding
 ↓
ViewModel
 ↓
Validation
 ↓
ModelState
 ↓
Controller Decision

The Part That Finally Made It Click for Me

The easiest way for me to remember ASP.NET Core validation is to stop thinking about ModelState as some mysterious framework feature.

It’s basically the application’s report card for the submitted form.

ModelState

Name              ✅
AccountType       ✅
StartingBalance   ❌

Then:

ModelState.IsValid

is simply asking:

Did everything pass?

If yes, continue.

If no, show the form again.

Once I started looking at it that way, the code became much easier to read.

And more importantly, I wasn’t just memorizing this anymore:

if (!ModelState.IsValid)
{
    return View(model);
}

I finally understood why it was there.

Leave a Reply