PhoneToolMX/PhoneToolMX.Models/CheckExtensionsAttribute.cs
2023-10-17 21:55:10 -07:00

26 lines
923 B
C#

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);
}
}
}