I created ViewModel class with my own validation attribute to check if uploaded file has expected extension(pdf,jpg):
public class TmpMyInvoiceDraftVM
{
public TmpMyInvoiceDraftVM()
{
this.AttachmentsInvoiceUploadedPartial = new List<HttpPostedFileBase>();
}
[Attachments]
public HttpPostedFileBase AttachmentsInvoiceUploadedPartial { get; set; }
[AttributeUsage(AttributeTargets.Property)]
private sealed class AttachmentsAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
HttpPostedFileBase file = value as HttpPostedFileBase;
if (file == null)
{
return ValidationResult.Success;
}
string ext = Path.GetExtension(file.FileName).ToLower();
if (String.IsNullOrEmpty(ext))
{
return new ValidationResult("File has no extension");
}
if (!ext.Equals(".pdf", StringComparison.OrdinalIgnoreCase) &&
!ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase))
{
return new ValidationResult("Permitted formats: pdf,jpg");
}
return ValidationResult.Success;
}
}
}
And it works properly.This class represents data on form in my asp.net mvc application. Now my task is to extend ViewModel to validate not one file but few files ->
public List<HttpPostedFileBase> AttachmentsInvoiceUploadedPartial { get; set; }
I have no idea how to write validation attribute to check all attachments. I even wonder if it’s possible to create such an attribute.. Can someone tell me how to build such an attribute or if it’s not possible tells what is better way to validate
List<HttpPostedFileBase>
? Thank you!