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 && value is bool && (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 && (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 && value is int && (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 && value is DateTime && ((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 && value is string &&
                   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

Paul Seal

Umbraco MVP and .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.

Proudly sponsored by

Moriyama

  • Moriyama build, support and deploy Umbraco, Azure and ASP.NET websites and applications.
AppVeyor

  • CI/CD service for Windows, Linux and macOS
  • Build, test, deploy your apps faster, on any platform.
elmah.io

  • elmah.io is the easy error logging and uptime monitoring service for .NET.
  • Take back control of your errors with support for all .NET web and logging frameworks.
uSync Complete

  • uSync.Complete gives you all the uSync packages, allowing you to completely control how your Umbraco settings, content and media is stored, transferred and managed across all your Umbraco Installations.
uSkinned

  • More than a theme for Umbraco CMS, take full control of your content and design with a feature-rich, award-nominated & content editor focused website platform.
UmbHost

  • Affordable, Geo-Redundant, Umbraco hosting which gives back to the community by sponsoring an Umbraco Open Source Developer with each hosting package sold.