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
Data type of the data field
Max. length of array or string data allowed
Min. length of array or string data allowed
Numeric range constraints for the data field value
Data field value must match the specified regular expression
Data field value is required
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
        [StringLength(30, MinimumLength = 6)]
        public string UserName { get; set; }

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

        [StringLength(255, MinimumLength = 8)]
        public string ConfirmPassword { get; set; }

        public string Email { get; set; }

        public string Phone { get; set; }

        public DateTime Birthday { get; set; }

        public string Remarks { get; set; }


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"?>
    <add key="webpages:Version" value="" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

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

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(