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

Want to thank me?

If I've helped you out and you want to thank me, why not buy me a coffee?

About the author

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.

Related Posts

How to create a dynamic image from multiple images using ImageProcessor

This post shows you how I created a handler to create dynamic header images for my umbraco website u…

Read Post

How to send Slack messages programmatically using C#

In this post I show you how you can send Slack messages programmatically using C#

Read Post

How to include scripts from partial views in MVC and Umbraco

This post will show you how you can include scripts from inside an MVC partial view rather than havi…

Read Post

How to fix the error "Authentication failed because the remote party has closed the transport stream"

This post will show you how to fix the error "Authentication failed because the remote party has clo…

Read Post