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?

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 solve the error assets file project.assets.json not found in Visual Studio

This post tells you how to solve the error assets file project.assets.json not found in Visual Studi…

Read Post

Code to help you debug an umbraco issue on a remote site

This post gives you some razor code to help you see the values of the IPublishedContent item's prope…

Read Post

How to set the default page base type to UmbracoViewPage in Umbraco

In this post I share with you what Ronald Barendse taught us about setting the pageBaseType in Umbra…

Read Post

How to fix corrupt accented characters in Excel for a C# export as CSV

This post will help you fix the issue where you csv export has corrupt characters when opening it in…

Read Post