Simple Validations
In this type we will see how to
use model state and the validation HTML helpers
Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcTextApplication.Models
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string email {
get; set; }
public DateTime
DOB { get; set;
}
}
}
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcTextApplication.Models;
namespace MvcTextApplication.Controllers
{
public class PersonController : Controller
{
List<Person>
people = new List<Person>();
public ActionResult Index()
{
Person per= new Person();
per.Id = 1;
per.Name = "Guugeaaa";
per.email = "Sample@gmail.com";
per.DOB = DateTime.Now;
people.Add(per);
List<Person>
fundlistnew;
fundlistnew = people;
var movies = fundlistnew;
return View(movies.ToList());
}
NOTE: Create View by right click on this
Action method
public ActionResult
Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult
Create([Bind(Exclude = "Id")] Person
person)
{
//
Validation logic
if
(person.Name == null)
ModelState.AddModelError("Name", "Name
is required not null.");
if
(person.Age == null)
ModelState.AddModelError("Age", "Age
is required.");
if
(person.DOB == null)
ModelState.AddModelError("DOB", "DOB
is required.");
if
(person.email == null)
{
ModelState.AddModelError("Email", "Email
is required.");
}
else
{
if (!System.Text.RegularExpressions.Regex.IsMatch(person.email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
{
ModelState.AddModelError("Email",
"Email format is invalid.");
}
}
//ModelState.IsValid
to check
whether the Person has any validation errors.
// Calling this
method evaluates any validation attributes that have been applied to the object.
// If the object
has validation errors, the
Create
method redisplays the form.
if
(!ModelState.IsValid)
{
return
View("Create", person);
}
//people.Add(person);
return RedirectToAction("Index");
}
}
HTML
Index Action method View
<p>
<%: Html.ActionLink("Create
New", "Create") %>
</p>
<table>
<tr>
<th></th> <th>Name</th><th> Age</th> <th> email</th> <th>DOB</th>
</tr>
<% foreach
(var item in
Model) { %>
<tr>
<td> <%: item.Name %></td>
<td> <%: item.Age %></td>
<td><%: item.email %></td>
<td>
<%: String.Format("{0:g}", item.DOB) %>
</td>
</tr>
<% } %>
</table>
Create Action method View
<h2>Create</h2>
<ul class="validation-summary-error" >
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors
and try again.") %>
</ul>
<% using
(Html.BeginForm()) { %>
<fieldset>
<legend>Person</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Name) %>
<%: Html.ValidationMessage("Name","*") %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Age) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Age) %>
<%: Html.ValidationMessage("Age",
"*") %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.email) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.email) %>
<%: Html.ValidationMessage("Email",
"*")%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.DOB) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.DOB) %>
<%: Html.ValidationMessage("DOB", "*")%>
</div>
<p>
<input type="submit"
value="Create"
/>
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back
to List", "Index") %>
</div>
OUTPUT
Note: Html.ValidationMessage is used when we need to
show error message as validation summary for that we must include <%= Html.ValidationSummary()%> otherwise error will not shown or we need to replace Html.ValidationMessage with Html.ValidationMessagefor to show inline error messages.
Here we passed a lambda expression that specifies the
Address
property. In
this case we do not need to explicitly specify name/id of the helper method
will take it from the property name
e.g. <%:
Html.ValidationMessageFor(model =>
model.Name) %>
Validations Using Data Annotation Validators
System.ComponentModel.DataAnnotations namespace to specify
validation for individual fields in the data model. These attributes define
common validation patterns, such as range checking and required fields.
The advantage of
using the Data Annotation validators is that they enable you to perform
validation simply by adding one or more attributes
Class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MvcTextApplication.Models
{
public class PersonType
{
public int Id { get; set; }
[Required(ErrorMessage = "Name
is required")]
[StringLength(10)]
[Display(Name = "PersonName")]
public string Name { get; set; }
[Required(ErrorMessage = "Age
is required")]
[Range(15, 35, ErrorMessage = "Age must be between 15 and 35")]
[Display(Name = "PersonAge")]
public int Age { get; set; }
[Required(ErrorMessage = "Email
is required")]
[RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$",
ErrorMessage = "Invalid Email Address")]
public string email {
get; set; }
[Required(ErrorMessage = "DOB
is required")]
[DisplayFormat(DataFormatString = "{0:c}")]
[Display(Name = "DateOfBirth")]
[RegularExpression(@"(0[1-9]|[12][0-9]|3[01])[-
/.](0[1-9]|1[012])[- /.](19|20)\d\d", ErrorMessage = "Invalid date e.g. 17/04/1981")]
public DateTime
DOB { get; set;
}
}
}
Note : In above
class attribute [Display(Name = "")]
will display Text on Create Page shown in fig below e.g. property Name
will be displayed as PersonName.
Controller
:
using System.Web.Mvc;
using MvcTextApplication.Models;
namespace MvcTextApplication.Controllers
{
public class PersonTypeController : Controller
{
List<PersonType>
people = new List<PersonType>();
//
// GET: /Person/
public ActionResult
Index()
{
PersonType per = new
PersonType();
per.Id = 1;
per.Name = "Guggeaaa";
per.Age = 30;
per.email = "Sample@gmail.com";
per.DOB = DateTime.Now;
people.Add(per);
List<PersonType>
fundlistnew;
fundlistnew = people;
var objperson = fundlistnew;
return View(objperson.ToList());
}
NOTE: Create View by right click on
this Action method
public ActionResult
Create()
{
return View();
}
NOTE: Don’t Create View from this Action method this method comes into
action on postback
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult
Create(PersonType person)
{
// When our HTML form is
posted back to the server, the this method will be called. Because the
action method accepts a “Person” //object as a parameter, ASP.NET MVC will
create a Person object and automatically map the incoming form input values to
it.
// it will
also check to see whether the DataAnnotation validation attributes for the
Person object are valid.
//If everything is valid, then the
ModelState.IsValid check within our code will redirect to Index Action method
otherwise errors .
// The error messages are then displayed within our view because
our Create form has <%= Html.ValidationMessageFor() %> helper method
calls next to each <%= Html.TextBoxFor() %> helper.
if (!ModelState.IsValid)
{
return View("Create",
person);
}
////people.Add(person);
return RedirectToAction("Index");
}
}
}
HTML:
Index Action method View
<h2>Index</h2>
<p>
<%: Html.ActionLink("Create
New", "Create") %>
</p>
<table>
<tr>
<th></th>
<th>Name</th><th> Age</th> <th> email </th> <th> DOB </th>
</tr>
<% foreach
(var item in
Model) { %>
<tr>
<td>
<%: Html.ActionLink("Edit",
"Edit", new
{ id=item.Id }) %>
|
<%: Html.ActionLink("Details",
"Details", new { id=item.Id }) %> |
<%: Html.ActionLink("Delete",
"Delete", new
{ id=item.Id }) %>
</td>
<td><%: item.Name %></td>
<td><%: item.Age %></td>
<td><%: item.email %></td>
<td><%: String.Format("{0:g}", item.DOB) %> </td>
</tr>
<% } %>
</table>
Create Action method View
<h4>Create</h4>
<script src="<%:
Url.Content("~/Scripts/jquery-1.4.4.min.js") %>"
type="text/javascript"></script>
<script src="<%:
Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%:
Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
<% using
(Html.BeginForm()) { %>
<fieldset>
<legend>PersonType</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Name) %>
<%:
Html.ValidationMessageFor(model => model.Name) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Age) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Age) %>
<%: Html.ValidationMessageFor(model => model.Age) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.email) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.email) %>
<%: Html.ValidationMessageFor(model => model.email) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.DOB) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.DOB) %>
<%: Html.ValidationMessageFor(model => model.DOB) %>
</div>
<p>
<input type="submit"
value="Create"
/>
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back
to List", "Index") %>
</div>
OutPut
**************************************************
**************************************************
Custom Annotations Validation Attribute :
Create CheckAgeAttribute Class IN
Model Folder. In this class we are checking age of person.where CheckAge is attribute name
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
public class CheckAgeAttribute : ValidationAttribute
{
private int _maxAGE;
public CheckAgeAttribute(int
MaxAge)
{
_maxAGE = MaxAge;
}
public override bool IsValid(object
value)
{
if (value == null) return true;
var dateofbirth = (DateTime)value;
double AgeValue = DateTime.Now.Subtract(dateofbirth).TotalDays
/ 365;
if (AgeValue < _maxAGE) return
false;
return true;
}
}
Let’s take above class Person Type
public class PersonType
{
public int Id { get; set; }
[Required(ErrorMessage = "Name
is required")]
[StringLength(10)]
[Display(Name = "PersonName")]
public string Name { get; set; }
[Required(ErrorMessage = "Age
is required")]
[Range(15, 35, ErrorMessage = "Age must be between 15 and 35")]
[Display(Name = "PersonAge")]
public int Age { get; set; }
[Required(ErrorMessage = "Email
is required")]
[RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$",
ErrorMessage = "Invalid Email Address")]
public string email {
get; set; }
[Required(ErrorMessage = "DOB
is required")]
[DisplayFormat(DataFormatString = "{0:c}")]
[Display(Name = "DateOfBirth")]
[CheckAge(18,ErrorMessage="You are not 18 years older" ) ]
public DateTime
DOB { get; set;
}
}
Out
Put:
Enabling Client-side Validation
Just put Three
highlighted yellow Lines at top of page
<h4>Create</h4>
<script src="<%: Url.Content("~/Scripts/jquery-1.4.4.min.js")
%>" type="text/javascript"></script>
<script src="<%:
Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%:
Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<%
Html.EnableClientValidation();%>
<% using
(Html.BeginForm()) { %>
<fieldset>
<legend>PersonType</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Name) %>
<span class="validation-summary-error"> <%:
Html.ValidationMessageFor(model => model.Name) %></span>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Age) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Age) %>
<span
class="validation-summary-error"> <%:
Html.ValidationMessageFor(model => model.Age) %></span>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.email) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.email) %>
<span class="validation-summary-error"> <%:
Html.ValidationMessageFor(model => model.email) %></span>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.DOB) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.DOB) %>
<span
class="validation-summary-error"> <%:
Html.ValidationMessageFor(model => model.DOB) %></span>
</div>
<p>
<input type="submit"
value="Create"
/>
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back
to List", "Index") %>
</div>
Validations with the IDataErrorInfo Interface :
Class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace MvcTextApplication.Models
{
public partial class Employee : IDataErrorInfo
{
private string
_firstName;
private string
_email;
private Dictionary<string, string>
_errors = new Dictionary<string, string>();
public string
FirstName {
get { return
_firstName; }
set {
if (String.IsNullOrEmpty(value))
_errors.Add("FirstName", "First Name is required");
_firstName = value;
}
}
public string Email
{
get { return _email;
}
set
{
if (String.IsNullOrEmpty(value))
{
_errors.Add("Email", "Email is
required");
}
else
{
if (!System.Text.RegularExpressions.Regex.IsMatch(value,
@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
{
_errors.Add("Email", "Email
format is invalid.");
}
}
_email = value;
}
}
public string Error
{
get { return String.Empty;
}
}
public string this[string
columnName]
{
get {
if (_errors.ContainsKey(columnName))
return _errors[columnName];
return String.Empty;
}
}
}
}
Model :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace MvcTextApplication.Models
{
public partial class Employee : IDataErrorInfo
{
private string
_firstName;
private string
_email;
private Dictionary<string, string>
_errors = new Dictionary<string, string>();
public string
FirstName {
get { return
_firstName; }
set {
if (String.IsNullOrEmpty(value))
_errors.Add("FirstName", "First Name is required");
_firstName = value;
}
}
public string Email
{
get { return _email;
}
set
{
if (String.IsNullOrEmpty(value))
{
_errors.Add("Email", "Email is
required");
}
else
{
if (!System.Text.RegularExpressions.Regex.IsMatch(value,
@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
{
_errors.Add("Email", "Email
format is invalid.");
}
}
_email = value;
}
}
public string Error
{
get { return String.Empty;
}
}
public string this[string
columnName]
{
get {
if (_errors.ContainsKey(columnName))
return _errors[columnName];
return
String.Empty;
}
}
}
}
Controller
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcTextApplication.Models;
namespace MvcTextApplication.Controllers
{
public class EmaployeeController : Controller
{
//
// GET: /Emaployee/
public ActionResult
Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Employee emp)
{
if (!ModelState.IsValid)
{
return View("Create",
emp);
}
////people.Add(person);
return RedirectToAction("Index");
}
}
}
View:
<h2>Create</h2>
<script src="<%:
Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%:
Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
<% using
(Html.BeginForm()) { %>
<%: Html.ValidationSummary(true)
%>
<fieldset>
<legend>Employee</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.FirstName) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.FirstName) %>
<span class="validation-summary-error">
<%: Html.ValidationMessageFor(model =>
model.FirstName) %></span>
</div>
<div class="editor-label">
<%: Html.LabelFor(model =>
model.Email) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Email) %>
<span class="validation-summary-error">
<%: Html.ValidationMessageFor(model => model.Email) %></span>
</div>
<p>
<input type="submit"
value="Create"
/>
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back
to List", "Index") %>
</div>
OutPut:
No comments :
Post a Comment