pwt-0x01-ng/Models/Validation/FileTypeAttr.cs

48 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
namespace pwt_0x01_ng.Models.Validation
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
public class FileTypeAttr : ValidationAttribute, IClientModelValidator
{
private readonly string type;
public FileTypeAttr(string type){
this.type = type.ToLower();
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if (value == null) {
/* img is optional as of now */
return ValidationResult.Success;
} else if (value is IFormFile iff) {
if(iff.ContentType.ToLower().Contains(type)) {
return ValidationResult.Success;
} else {
return new ValidationResult(GetErrorMessage(validationContext.MemberName), new List<string> { validationContext.MemberName });
}
}
throw new NotImplementedException($"Attribute {nameof(FileTypeAttr)} not implemented for object {value.GetType()}.");
}
protected string GetErrorMessage(string member_name) => $"make sure the {member_name} you picked really is of type <code>{type}/*</code>. <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types\" title=\"help\" target=\"_blank\" rel=\"noopener noreferer\"><em>help</em></a>";
public void AddValidation(ClientModelValidationContext ctx){
MergeAttribute(ctx.Attributes, "data-val", "true");
MergeAttribute(ctx.Attributes, "data-val-content", GetErrorMessage("file"));
MergeAttribute(ctx.Attributes, "data-val-content-type", type);
}
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value){
if (attributes.ContainsKey(key)){
return false;
}
attributes.Add(key, value);
return true;
}
}
}