MVC Custom Model Property Validation Attributes

Posted written by Paul Seal on January 19, 2016 .NET Framework

This post shows you how to create your own custom validation attributes in MVC.
You can then decorate your model properties with them on your forms.

Let's say you have a form with a checkbox on it for accepting the terms and conditions and you don't want the user to be able to continue until the have accepted the the terms and conditions, you can add the MustBeTrue attribute in the below code and it will enforce this rule.

Create a file to reference in your model.

using System;
using System.ComponentModel.DataAnnotations;

namespace CodeShare.Library.Validation
{

    /// <summary>
    /// Checks if the value is not null and is a bool and is equal to true
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeTrue : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return value != null &amp;&amp; value is bool &amp;&amp; (bool) value;
        }
    }

    /// <summary>
    /// Checks if the value is equal to null or is an empty string
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeEmpty : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return value == null || (value is string &amp;&amp; (string) value == "");
        }
    }

    /// <summary>
    /// Checks if the value is not null and is an integer which is greater than zero
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class GreaterThanZero : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return value != null &amp;&amp; value is int &amp;&amp; (int) value > 0;
        }
    }

    /// <summary>
    /// Checks if their 18th birthday is not in future.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class OverEighteenYearsOld : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return value != null &amp;&amp; value is DateTime &amp;&amp; ((DateTime) value).AddYears(18).Date <= DateTime.Now.Date;
        }
    }

    /// <summary>
    /// Checks if it the string is a valid UK date
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class ValidStringAsUKDate : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime testDate = new DateTime();
            return value == null || (value != null &amp;&amp; value is string &amp;&amp;
                   DateTime.TryParse((string) value, new System.Globalization.CultureInfo("en-GB"),
                       System.Globalization.DateTimeStyles.None, out testDate));
        }
    }

}

Here is an example of how you would use it.

using System.ComponentModel.DataAnnotations;
using CodeShare.Library.Validation;




namespace CodeShare.Web.Models
{
    public class NewsletterSignupModel
    {

        [Required]
        public string Name { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [MustBeTrue]
        public bool AcceptTerms { get; set; }

    }
}

I hope you find it useful.

If you'd like to know more about the fundamentals of MVC, why not use your 10 day free trial with pluralsight to go through ASP.NET MVC 5 Fundamentals

Thanks

Paul