Subscribe

Close

Thank you for visiting!

Please consider subscribing to the RSS feed or following me on Twitter.

Basic ASP.NET MVC Form Validation

Later versions of ASP.NET MVC utilizes jQuery Validate for form validation, and does it well. A few things must be in place for this to work.

I'm going to show you a simple form with a text field and an email address, both of which are required. The email address will also be validated as an email address.

First of all, make sure you use the needed jQuery files. It's important that we use jQuery validate unobtrusive.

The easiest thing here is to install the Nuget package Microsoft.jQuery.Unobtrusive.Validation using Package Manager Console in Visual Studio:

Install-Package Microsoft.jQuery.Unobtrusive.Validation

(Otherwise, you can find the CDN:s on www.asp.net/ajax/cdn)

Don't forget to add the script elements for jQuery and jQuery unobtrusive. It's up to you if you go with the minified versions or the standard versions.

Next up, we will add two properties to our model, preferably a ViewModel.

ViewModel:

[Required(ErrorMessage = "*")]
[EmailAddress(ErrorMessage = "*")]
public string Email { get; set; }

[Required(ErrorMessage = "*")]
public string Name { get; set; }

First of all, we declare our properties. We decorate them with the Required and EmailAddress attributes. We need to import the System.ComponentModel.DataAnnotations namespace for this.

As you can see, you can define an error message for both the Required attribute as well as the EmailAddress attribute. I've chosen to just use an asterisk for both now.

Next up, we will render our form:

@using (Html.BeginForm("MyForm", null, FormMethod.Post))
{
<fieldset>
     <p>
	@Html.LabelFor(x => x.Email, "Email")
	@Html.TextBoxFor(x=>x.EmailTo, new { @placeholder="Email"})
	@Html.ValidationMessageFor(x => x.EmailTo)
     </p>
     <p>
	@Html.LabelFor(x => x.Name, "Name")
	@Html.TextBoxFor(x => x.Name, new { @placeholder = "Name" })
	@Html.ValidationMessageFor(x => x.Name)
     </p>
     <p>
        <input type="submit" value="Send" />
     </p>
</fieldset>
}

What is important here is that we use the TextBoxFor and ValidationMessageFor HTML helpers. ValidationMessageFor is what helps us display the error messages we configured in the view model.

Finally, you might want to style the HTML rendered when there's a field with a validation error. There are a few options, styling the input-validation-error css class takes you far.

And this is it! It's all you need to get started with form validation in ASP.NET MVC.

Here are a few useful links if you want to dive deeper into this:

To the top