In the context of ASP.NET Core MVC web applications, both model binding and model validation are processes that take place prior to the execution of a controller action. It is imperative for the application to examine the ModelState.IsValid and respond accordingly.

This rule enforces the developer to validate the model within a controller action, ensuring the application’s robustness and reliability.

Why is this an issue?

Querying the ModelState.IsValid property is necessary because it checks if the submitted data in the HTTP request is valid or not. This property evaluates all the validation attributes applied on your model properties and determines whether the data provided satisfies those validation rules.

What is the potential impact?

Skipping model validation can lead to:

Therefore, it’s highly recommended to always validate models in your application to ensure data integrity, application stability, and a good user experience.

While client-side validation enhances user experience by providing immediate feedback, it’s not sufficient due to potential manipulation of client-side code, browser compatibility issues, and dependence on JavaScript. Users can bypass or disable it, leading to invalid or malicious data being submitted. Therefore, server-side validation is essential to ensure data integrity and security, making it a best practice to use both client-side and server-side validation in your application.

Exceptions

How to fix it

If ModelState.IsValid returns true, it means that the data is valid and the process can continue. If it returns false, it means that the validation failed, indicating that the data is not in the expected format or is missing required information.

In such cases, the controller action should handle this by returning an appropriate response, such as re-displaying the form with error messages. This helps maintain the integrity of the data and provides feedback to the user, enhancing the overall user experience and security of your application.

Code examples

Noncompliant code example

public async Task<IActionResult> Create(Movie movie) // Noncompliant: model validity check is missing
{
    _context.Movies.Add(movie);
    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}

Compliant solution

public async Task<IActionResult> Create(Movie movie)
{
    if (!ModelState.IsValid)
    {
        return View(movie);
    }

    _context.Movies.Add(movie);
    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}

Resources

Documentation