Click to confirm

If you need a validation attribute on your input object that simply requires the user to tick a box to confirm something, you can use the following

using System.ComponentModel.DataAnnotations;

namespace YourApp.Validation;

public class MustConfirmAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object? value, ValidationContext validationContext) =>
        value is bool boolValue && boolValue == true
        ? ValidationResult.Success!
        : new ValidationResult(ErrorMessage ?? "Please confirm");
}

The class is then consumed like so

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

  [MustConfirm]
  public bool Confirmation { get; set; }
}

This will work with any app that uses Data Annotations as a form of validation, such as ASP.NET MVC apps or Blazor.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *