Asp.net MVC Form input validation example

Form validation is one of the most important aspect of web based application development, controlling what type of data user can submit to our database will decide the success factors of business, so data validation is important.

Here you learn how to validate asp.net mvc form input using model validation techniques.

Asp.net MVC Form Validation using DataAnnotations
In application development most of the time you work with form, where you accept data from user, so before you store data to database you should validate the data while user submitting the form.

How to use form validation message in mvc

You can display validation message with each field, this is more convenient way of showing validation message, and user find it easy and rectify the input data immediately there.

Name
Email

Here is how you the code will look like.

 @using (Html.BeginForm("actionName","controllerName", FormMethod.Post))
{   
<div>Name</div>
@Html.TextBoxFor(m => m.GuestName)
<div>@Html.ValidationMessageFor(m => m.GuestName)</div>
<div>Email</div>
@Html.TextBoxFor(m => m.GuestEmail)
<div>@Html.ValidationMessageFor(m => m.GuestEmail)</div> 

<input type="submit" value="Submit" />
}         

Form Validation in Asp.net MVC

You will learn Form Validation in Asp.net MVC, how to implement DataAnnotations attributes to implement validations. DataAnnotations provides built-in validation attributes for different type of data and validation rules.

DataAnnotations classes comes under System.ComponentModel.DataAnnotations; namespace In MVC we can write validation on each property of model class, we fix the data type, data length etc, let's look at the example below

Following model we have two properties guest name and email, we learn required field validation and email validation, as you can see on each property we have set the attribute.

using System.ComponentModel.DataAnnotations;    
public class GuestModel 
{
    [Required(ErrorMessage = "Your name Required")]
    [StringLength(50, ErrorMessage = "5 to 50 characters.", MinimumLength = 3)]
    public string GuestName { get; set; }
    
    [Required(ErrorMessage = "Email Required")] 
    [EmailAddress(ErrorMessage = "Invalid email")]
    public string GuestEmail { get; set; }
}
MVC form validation using DataAnnotations

Here are some Asp.net MVC DataAnnotations validation attributes with example

  • Required

    this will indicates that the property is a required field

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

    Validates with email address format

    [EmailAddress(ErrorMessage = "Invalid email")]
    public string GuestEmail { get; set; }
    
  • RegularExpression

    Specifies that the field value must match with specified Regular Expression

  • FileExtension

    Used for Validating with file extension

  • MaxLength

    String: maximum length for a string field

  • MinLength

    String: minimum length for a string field

  • Phone

    Specifies that the field is a phone number using regular expression for phone numbers

  • CreditCard

    Specifies that the specified field is a credit card number

  • CustomValidation

    This is for building custom validation rules as per business requirement, then can use that attribute as custom validator

ValidationSummary in ASP.NET MVC

When you want to display all validation message in one place then use ValidationSummary

Name
Email

ValidationMessageFor is in-built for each Html control in MVC, whatever ErrorMessage specified in the model, that will appear on screen as validation message.

You can display all validation message together or each message on field itself. Here is an example how you can display the validation message exactly above the field.

@model AppName.Models.GuestModel
<div>Your Email</div>
@Html.TextBoxFor(m => m.GuestEmail, new { style = "width:300px;" })
<div>@Html.ValidationMessageFor(m => m.GuestEmail)</div>

if you want to display all validation message together, then use @Html.ValidationSummary() somewhere inside the form.

ASP.Net MVC Range Validation Example

In Range validation you can specify minimum and maximum number (or any other data type like date, double etc.)

[Required(ErrorMessage = "Your age Required")]
[Range(22, 60, ErrorMessage = "Age between 22 to 60 only")]
public int Age { get; set; }
Custom Validation in ASP.Net MVC

Custom validator is required when you have some complex business logic to check with backend data, which may differ from user to user.

In such situation you have to write a custom class inherited from ValidationAttribute, here is the example

using System.ComponentModel.DataAnnotations;
public class WTRCustomValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value,  ValidationContext validationContext)
    {
        if (value != null)
        {
            bool result = false;
            string userInput = value.ToString();
            // here you have the value from user input
            // write whatever logic you want
                
            if (result)
            {
                return ValidationResult.Success;
            }
            else
            {                    
                return new ValidationResult("Incorrect data");
            }
        }
        else
        {
            return new ValidationResult(validationContext.DisplayName + " is required");
        }
    }
}

Now you can use the above custom validator with right property in your model as an attribute. here in example we are checking if BusinessCode value is correct

    public class CustomerModel  
    { 
        [WTRCustomValidator]  
        public string BusinessCode { get; set; }                 
    }  
Add JQuery for Validation

You must add JQuery reference for Validation to happen immediately on submit button click, else the form will get submitted to server side then the validation will fire

  
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Hope you learned all validation technique in Asp.Net MVC.

You also should learn

 
Form Validation in Asp.net MVC
Aspnet MVC Training
Asp.net MVC tutorials, learn model view controllers with c#, develop database driven web application using Asp.net MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial