Book a consultation

30 minute meeting

Thank you

We’ll reach out within one business day. If you don’t hear from us, check spam and promotions folders.

Contact us

Fill out the form to send us a message

Attach related materials (.pdf, .docx, .odt, .rtf, .txt, .pptx; max 5 MB)
Or

10.8.2009

4 min read

Creating validation in ASP.NET MVC 1.0

This is an article from the ASP.NET MVC software development series. This article describes one method of performing validation in an ASP.NET MVC application. In this tutorial, you learn how to move your validation logic out of your controllers and into a separate layer. The goal of this post is to describe one method of performing validation in an ASP.NET MVC application (asp.net mvc outsourcing). In this post, I’ll show how to move validation logic out of controllers and into a separate service layer. Integrating validation and business logic is a key part of any application that works with data. For the beginning I would like to describe steps of building the validation.

Creating Data Model Classes with LINQ to SQL

LINQ to SQL enables us to quickly create data model classes from existing database schema. To-do this we’ll open the database in the Server Explorer, and select the Tables we want to model in it. Imagine we have a LINQ to SQL data model, containing UserSettings and aspnet_User from the Simple_db database. As you may know, LINQ to SQL will generate these classes as partial classes, which we can use to extend this domain object’s behaviour Selecting tables, which need modeling in database. We can then drag the tables onto the LINQ to SQL designer surface. When we do this LINQ to SQL will automatically create classes using the schema of the tables (with class properties that map to the database table columns). Visual Studio automatically generates .NET classes that represent the models and database relationships defined using the LINQ to SQL designer. A LINQ to SQL Data Context class is also generated for each LINQ to SQL designer file added to the solution.

Integrating Validation and Business Logic with Model Classes

Bind(Include="UserId, FirstName, LastName, BirthDate, Address, Email, Phone")]
public partial class UserSettings
{
public bool IsValid
{
get { return (GetViolations().Count() == 0); }
}
 
public IEnumerable<ErrorInfo> GetViolations()
{
if (String.IsNullOrEmpty(FirstName))
yield return new ErrorInfo("First Name is required", "FirstName");
 
if (String.IsNullOrEmpty(LastName))
yield return new ErrorInfo("Last Name is required", "LastName");
 
if (BirthDate > DateTime.Today)
yield return new ErrorInfo("Date of birth later current date", "BirthDate");
 
if (!Validation.IsValidate(Email, PatternType.Email))
yield return new ErrorInfo("Email address isn't correct format", "Email");
 
if (!Validation.IsValidate(Phone, PatternType.Phone))
yield return new ErrorInfo("Phone number isn't correct format", "Phone");
 
yield break;
}
}
//Controller helper
public static class ModelStateHelpers
{
 
public static void AddModelErrors(this ModelStateDictionary modelState,
IEnumerable<ErrorInfo> errors)
{
 
foreach (ErrorInfo issue in errors)
{
modelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
}
}
//Validation class helper
public class Validation
{
public static bool IsValidate(string value, PatternType pattern)
{
string patternValue = "";
switch (pattern)
{
case PatternType.Email:
patternValue = @"^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$";
break;
case PatternType.Phone:
patternValue = @"^[+][0-9]\d{2}-\d{3}-\d{4}$";
break;
}
 
Regex regex = new Regex(patternValue);
return regex.IsMatch(value);
}
}
 
public enum PatternType
{
Email,
Phone
}

Creating a DataAdapter for manipulations with Data Models

public class DataAdapter
{
validation.Models.ModelClassesDataContext db = new ModelClassesDataContext();
 
public UserSettings GetUserSettings(Guid UserId)
{
return db.UserSettings.SingleOrDefault(u => u.UserId == UserId);
}
 
public UserSettings GetUserSettings(string UserName)
{
var user = db.aspnet_Users.SingleOrDefault(u => u.UserName == UserName);
return db.UserSettings.SingleOrDefault(s => s.UserId == user.UserId);
}
 
public void Insert(UserSettings us)
{
db.UserSettings.InsertOnSubmit(us);
}
 
public void Update(UserSettings us)
{
var old = GetUserSettings(us.UserId);
 
old.FirstName = us.FirstName;
old.LastName = us.LastName;
old.Address = us.Address;
old.BirthDate = us.BirthDate;
old.Phone = us.Phone;
old.Email = us.Email;
}
 
public void Save()
{
db.SubmitChanges();
}
}

Adding a UserSettings Actions in Account Controller

[Authorize]
public ActionResult UserSettings()
{
var us = db.GetUserSettings(User.Identity.Name);
if (us == null)
{
var user = db.GetUser(User.Identity.Name);
us = new UserSettings
{
UserId = user.UserId,
FirstName = "",
LastName = "",
Address = "",
BirthDate = DateTime.Parse("01.01.1900"),
Email = "",
Phone = ""
};
db.Insert(us);
db.Save();
}
return View(us);
}
 
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult UserSettings(validation.Models.UserSettings us)
{
if (us.IsValid)
{
db.Update(us);
db.Save();
 
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelErrors(us.GetViolations());
return View(us);
}
}

Adding a UserSettings View

During the development of the controller action method, creating a corresponding view is very straightforward. To create a new view for the current controller action, right-click somewhere on the method body, and select Add view... from the context menu. The following dialog box will be displayed. Dialog box. In the Add view dialog box, some options can be specified. First of all, the view name can be modified if required. By default, this name will be the same as the action method name. It's also possible to select a view template, which we will set to Empty. This template can be used to easily create a view for example, one which shows the details of an employee. Within our UserSettings() action method we attempt to retrieve a UserSettings object using the id provided within the URL. If a valid UserSettings is found we call the View() helper method, indicating we want to use a “UserSettings” view template to render the retrieved UserSettings object.

<%= Html.ValidationSummary() %>
<% using (Html.BeginForm(Model)) { %>
<div>
<fieldset>
<legend>User Settings</legend>
<p>
<label for="FirstName">First Name:</label>
<%= Html.TextBox("FirstName", Model.FirstName) %>
<%= Html.ValidationMessage("UserName") %>
</p>
<p>
<label for="LastName">Last Name:</label>
<%= Html.TextBox("LastName", Model.LastName) %>
<%= Html.ValidationMessage("LastName") %>
</p>
<p>
<label for="BirthDate">Barth Date:</label>
<%= Html.TextBox("BirthDate", Model.BirthDate ) %>
<%= Html.ValidationMessage("BirthDate")%>
</p>
<p>
<label for="Address">Address:</label>
<%= Html.TextBox("Address", Model.Address ) %>
<%= Html.ValidationMessage("Address") %>
</p>
<p>
<label for="Email">Email:</label>
<%= Html.TextBox("Email", Model.Email ) %>
<%= Html.ValidationMessage("Email") %>
</p>
<p>
<label for="Phone">Phone:</label>
<%= Html.TextBox("Phone", Model.Phone) %>
<%= Html.ValidationMessage("Phone")%>
</p>
<p>
<input type="submit" value="Update" />
</p>
</fieldset>
</div>
<% } %>
</asp:Content>

Now, because we already have Html.ValidationMessage() helpers in the view, our error messages will appear: Error messages box in MVC application.

Summary:

The aim of this post was to discuss one approach to performing validation in an ASP.NET MVC application. In this post, I showed how to move all of your validation logic out of your controllers and into a separate service layer. Hope it was of some help to you.

References:

ASP.NET MVC The Official Microsoft ASP.NET Site ScottGU’s Blog Documentation   Denis K., .NET team, Binary Studio

Thank you

We’ll reach out within one business day. If you don’t hear from us, check spam and promotions folders.

Looking for a tech partner to help you scale your project?

Let’s schedule a quick call to explore how we can support your business objectives.

Christina Berko

Let’s schedule a quick call to explore how we can support your business objectives.

Christina Berko

Client Manager

0 Comments
name *
email *

Featured Case Studies