Tag: Validation

ASP.NET MVC Model Validation using Data Annotations

In ASP.NET MVC, there are several ways to validate the model data prior to saving the data into the data store.
1. Validate the model data explicitly
2. Implement the IValidateableObject interface
3. Specify Data Annotations [Recommended]

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.

Built-in Data Annotations

Namespace: System.ComponentModel.DataAnnotations

Validation Attribute Description
CompareAttribute Compares two properties
CustomValidationAttribute Specifies a custom validation method
DataTypeAttribute
Data type of the data field
MaxLengthAttribute
Max. length of array or string data allowed
MinLengthAttribute
Min. length of array or string data allowed
RangeAttribute
Numeric range constraints for the data field value
RegularExpressionAttribute
Data field value must match the specified regular expression
RequiredAttribute
Data field value is required
StringLengthAttribute
Min. and max. length of characters that are allowed in a data field

Namespace: System.Web.Security

Validation Attribute Description
MembershipPasswordAttribute Validates whether a password field meets the current password requirements for the membership provider

Code Sample

using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Security;

namespace AspNetMvc.Models
{
    public class User
    {
        [DataType(DataType.Text)]
        [StringLength(30, MinimumLength = 6)]
        [Required()]
        public string UserName { get; set; }

        [DataType(DataType.Password)]
        [StringLength(255, MinimumLength = 8)]
        [Required()]
        [MembershipPassword()]
        public string Password { get; set; }

        [Compare("Password")]
        [DataType(DataType.Password)]
        [StringLength(255, MinimumLength = 8)]
        [Required()]
        [MembershipPassword()]
        public string ConfirmPassword { get; set; }

        [DataType(DataType.EmailAddress)]
        [StringLength(128)]
        [Required()]
        public string Email { get; set; }

        [DataType(DataType.PhoneNumber)]
        [RegularExpression("^[0-9]{8}$")]
        [StringLength(32)]
        public string Phone { get; set; }

        [DataType(DataType.Date)]
        public DateTime Birthday { get; set; }

        [DataType(DataType.MultilineText)]
        [StringLength(255)]
        public string Remarks { get; set; }
    }
}

Screenshots

ASP.NET MVC Validation (Required)
ASP.NET MVC Validation (Required)
ASP.NET MVC Validation (StringLength, DataType, RegularExpression)
ASP.NET MVC Validation (StringLength, DataType, RegularExpression)
ASP.NET MVC Validation (Compare)
ASP.NET MVC Validation (Compare)

Client-side Validation
1. Edit the ~\web.config file as the following

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>

2. Check the ~\App_Start\BundleConfig.cs file to include the following line

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
			"~/Scripts/jquery.validate.unobtrusive*",
			"~/Scripts/jquery.validate*"));

References