MVC 8 Validation
MVC 8 Validation
Data Annotation is recommended because there are built-in Data Annotations in .NET
Framework. You don’t have to implement your own validation logic, instead
specifying the Validation Data Annotation that you need. The Data Annotations
specified support both server-side & client-side validation. In case the built-in cannot
fulfill your requirements, you can also implement your own Data Annotation.
Namespace: System.ComponentModel.DataAnnotations
Validation Attribute Description
RegularExpressionAttribute Data field value must match the specified regular expression
StringLengthAttribute Min. and max. length of characters that are allowed in a data field
Namespace: System.Web.Security
Validates whether a password field meets the current password requirements for the
MembershipPasswordAttribute
membership provider
Code Sample
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Security;
1 namespace AspNetMvc.Models
2 {
3 public class User
4 {
5 [DataType(DataType.Text)]
6 [StringLength(30, MinimumLength = 6)]
7 [Required()]
8 public string UserName { get; set; }
9
10 [DataType(DataType.Password)]
11 [StringLength(255, MinimumLength = 8)]
12 [Required()]
13 [MembershipPassword()]
14 public string Password { get; set; }
15
16 [Compare("Password")]
17 [DataType(DataType.Password)]
18 [StringLength(255, MinimumLength = 8)]
19 [Required()]
20 [MembershipPassword()]
21 public string ConfirmPassword { get; set; }
22
23 [DataType(DataType.EmailAddress)]
24 [StringLength(128)]
25 [Required()]
26 public string Email { get; set; }
27
28 [DataType(DataType.PhoneNumber)]
29 [RegularExpression("^[0-9]{8}$")]
30 [StringLength(32)]
31 public string Phone { get; set; }
32
33 [DataType(DataType.Date)]
34 public DateTime Birthday { get; set; }
35
[DataType(DataType.MultilineText)]
[StringLength(255)]
public string Remarks { get; set; }
}
}
Snapshot
On to the Preview
Let’s say you had the following “Customer” domain model (or view model, depending on
your project structure) in an MVC 6 project:
[Integer]
[Min(1, ErrorMessage="Unless you are benjamin button you a
re lying.")]
[Required]
public int Age { get; set; }
[FileExtensions("png|jpg|jpeg|gif")]
public string ProfilePictureLocation { get; set; }
}
Now let’s try to put in some invalid values and see what happens:
[HttpPost]
public ActionResult Create(User user)
{
if (!ModelState.IsValid)
{
return View(user);
}
@model NuGetValidationTester.Models.User
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusi
ve.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
@Html.EditorForModel()
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
In the Create.cshtml view, note that we are referencing jquery validation and jquery
unobtrusive (jquery is referenced in the layout page). These MVC 3 included scripts are
the only ones you need to enjoy both the basic Data Annotations validation as well as the
validation additions available in Data Annotations Extensions. These references are
added by default when you use the MVC 3 “Add View” dialog on a modification template
type.
Now when we go to /User/Create we should see a form for editing a User
Email address validation
use EmailAddress Attribute which resides
inside System.ComponentModel.DataAnnotations.
Your code should look similar to this:
using the [Range(min, max)]validator this far for checking values, like e.g.:
[Range(1, 10)]
public int SomeNumber { get; set; }
However - now I need to check the min and max condition separately. I
expected to find attributes like these:
{
[Required]
[Email]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[Required]
[EqualTo("Password")]
public string PasswordConfirm { get; set; }
[Url]
public string HomePage { get; set; }
[Integer]
[Min(1)]
public int Age { get; set; }
}
Now let’s re-run our form and try to use some invalid values: