Online Training for MVC Web Designing Development, MS SQL, Digital Marketing

Validation in MVC

In application development most of the times you work with form, where you accept data from user, now before you can store data into database, you have to validate the data.

In this article you will learn how to implement data validations in the ASP.NET MVC application

Form Validation in MVC ?

You will learn Form Validation in 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; }

DataAnnotations validation attributes in MVC

Attribute Description
Required this will indicates that the property is a required field
EmailAddress Validates with email address format
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

ValidationMessage, ValidationSummary in ASP.NET MVC

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.
Range Validation in ASP.Net MVC
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  
        public string BusinessCode { get; set; }                 

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

Data Validation in MVC

Group Training