2019-07-18 10:02:42 +02:00
|
|
|
|
using System;
|
|
|
|
|
using System.ComponentModel.DataAnnotations;
|
2019-08-14 12:20:53 +02:00
|
|
|
|
|
|
|
|
|
// ReSharper disable UnusedMember.Global
|
2019-07-18 10:02:42 +02:00
|
|
|
|
|
|
|
|
|
namespace Tapeti.DataAnnotations.Extensions
|
|
|
|
|
{
|
2019-08-14 12:20:53 +02:00
|
|
|
|
/// <inheritdoc />
|
2019-07-18 10:02:42 +02:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// Can be used on Guid fields which are supposed to be Required, as the Required attribute does
|
|
|
|
|
/// not work for Guids and making them Nullable is counter-intuitive.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class RequiredGuidAttribute : ValidationAttribute
|
|
|
|
|
{
|
|
|
|
|
private const string DefaultErrorMessage = "'{0}' does not contain a valid guid";
|
|
|
|
|
private const string InvalidTypeErrorMessage = "'{0}' is not of type Guid";
|
|
|
|
|
|
2019-08-14 12:20:53 +02:00
|
|
|
|
/// <inheritdoc />
|
2019-07-18 10:02:42 +02:00
|
|
|
|
public RequiredGuidAttribute() : base(DefaultErrorMessage)
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
|
2019-08-14 12:20:53 +02:00
|
|
|
|
/// <inheritdoc />
|
2019-07-18 10:02:42 +02:00
|
|
|
|
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
|
|
|
|
|
{
|
|
|
|
|
if (value == null)
|
|
|
|
|
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
|
|
|
|
|
|
|
|
|
|
if (value.GetType() != typeof(Guid))
|
|
|
|
|
return new ValidationResult(string.Format(InvalidTypeErrorMessage, validationContext.DisplayName));
|
|
|
|
|
|
|
|
|
|
var guid = (Guid)value;
|
|
|
|
|
return guid == Guid.Empty
|
|
|
|
|
? new ValidationResult(FormatErrorMessage(validationContext.DisplayName))
|
|
|
|
|
: null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|