PhoneToolMX/PhoneToolMX.Models/CheckExtensionsAttribute.cs

26 lines
923 B
C#
Raw Normal View History

2023-10-18 04:55:10 +00:00
using PhoneToolMX.Models.ViewModels;
using System.ComponentModel.DataAnnotations;
using System.Data;
namespace PhoneToolMX.Models
{
public class CheckExtensionsAttribute : ValidationAttribute
{
private int? MaxExtensions;
public override string FormatErrorMessage(string name)
{
return MaxExtensions != null
? $"Up to {MaxExtensions} extensions can be assigned to this phone"
: "Too many extensions assigned to this phone";
}
public override bool IsValid(object value)
{
if (value is not PhoneVM phone) throw new ConstraintException($"{GetType().Name} is only allowed for PhoneVM");
if (phone.MaxExtensions <= 0 || phone.Extensions == null) return true;
MaxExtensions = phone.MaxExtensions;
return !(phone.Extensions.Count > phone.MaxExtensions);
}
}
}