3

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!

Roman
  • 63
  • 5
  • You can create new validations attribute and cast the value to List and then do the validation on all of the items. – ssimeonov Apr 15 '16 at 10:41
  • Maybe i didnt understand what you wrote. You mean to cast the object value to List ? – Roman Apr 15 '16 at 11:01
  • Yes! But you have to create a new attribute, because you won't be able to create one attribute that can handle a single object and list of objects. So you can create AttachmentsListAttribute and then cast the value to List. – ssimeonov Apr 15 '16 at 11:40
  • #ssimeonov I understood what you mean.. i think that your idea is good. – Roman Apr 15 '16 at 11:44

0 Answers0