ASP.NET Web Pages Validating Forms

We recently discovered that the ModelState class includes a method called IsValid which basically validates forms, which we weren't aware of before. If you been following our ASP.NET Web Pages tutorials you will realize  that we usually used a nested If Else statement to validate user input, which is perfectly fine. However, this ModelState.isValid method is possibly a better way to do it, plus it will display multiple errors.

In the following example we create a page named form.cshtml and simply get the user's first name and surname, making sure they are not empty and making sure that first name is not longer than 5 and the surname is not less than 3.

C# Code


var forename = "";
var surname = "";
var msg = "";

if (IsPost)

    forename = Request["forename"];
    surname = Request["surname"];

  if (forename.IsEmpty())
         ModelState.AddError("forename", "Please enter a value");

    if (forename.Length > 5)
        ModelState.AddError("forename", "Sorry forename is too long");

  if (surname.IsEmpty())
          ModelState.AddError("surname", "Please enter a value");

    if (surname.Length < 3)
        ModelState.AddError("surname", "Sorry surname is too short");

    if (ModelState.IsValid)
        msg = "<p> Welcome " + forename + " " + surname + "</p>";



Here there are multiple If Else statements which check different conditions, and at the end is an If Else statement which checks to see if the form is valid.


<!DOCTYPE html>
<html lang="en">
        <meta charset="utf-8" />

        <form method="post">
        <input type="text" name="forename"/>

            <input type="text" name="surname" />

            <input type="submit"/>


The benefit of isValid is that when multiple errors occur it will show them, while an If Else statement will not do this. It is recommended you use the ModelState.IsValid method to validate client input.