chore: add image validation
This commit is contained in:
parent
ff301397ff
commit
484d9a2db5
|
@ -1,6 +1,7 @@
|
|||
using Microsoft.AspNetCore.Http;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using pwt_0x01_ng.Models.Validation;
|
||||
|
||||
namespace pwt_0x01_ng.Models
|
||||
{
|
||||
|
@ -10,6 +11,7 @@ namespace pwt_0x01_ng.Models
|
|||
[Required]
|
||||
public string DataTarget { get; set; }
|
||||
[NotMapped]
|
||||
[FileTypeAttr("image")]
|
||||
public IFormFile Image { get; set; }
|
||||
[Required]
|
||||
[StringLength(255)]
|
||||
|
|
|
@ -0,0 +1,47 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace pwt_0x01_ng.Models.Validation
|
||||
{
|
||||
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 your {member_name} really is an image ({type}).";
|
||||
|
||||
public void AddValidation(ClientModelValidationContext ctx){
|
||||
MergeAttribute(ctx.Attributes, "data-val", "true");
|
||||
MergeAttribute(ctx.Attributes, "data-val-content", GetErrorMessage("File"));
|
||||
MergeAttribute(ctx.Attributes, "data-val-filetype", type);
|
||||
}
|
||||
|
||||
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value){
|
||||
if (attributes.ContainsKey(key)){
|
||||
return false;
|
||||
}
|
||||
|
||||
Attributes.Add(key, value);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -28,6 +28,7 @@
|
|||
<Folder Include="Migrations\pgsql" />
|
||||
<Folder Include="Models\Database" />
|
||||
<Folder Include="Models\Database\Conf" />
|
||||
<Folder Include="Models\Validation" />
|
||||
<Folder Include="wwwroot\images\carousels" />
|
||||
<Folder Include="wwwroot\images\products" />
|
||||
</ItemGroup>
|
||||
|
|
Reference in New Issue