Is it possible to validate the import of an excel file with regular expression?

2

I'm importing an excel file using asp.net and validate to see if it's really an excel or not. I do not want to use if and else , so I'm trying to do this through annotations .

My main idea now is to use regular expressions , I found some on the internet to validate excel, I tried all but they always return the message saying that the file is not excel, even when it is the types of files I post are being invalidated.)

Does anyone know if it is really possible to do this validation in ASP.NET with these reg. expressions

Here is the model code I'm trying to validate:

    [RegularExpression(@"^ (?:[\w]\:|\)(\[a-z_\-\s0-9\.]+)+\.(xls|xlsx)$
        ", ErrorMessage = "O arquivo selecionado precisa ser um excel")]
    [Required]
    [Display(Name = "Arquivo Excel")]
    public HttpPostedFileBase ArquivoExcel { get; set; }
    
asked by anonymous 15.12.2015 / 20:49

1 answer

1

Make a file validation attribute:

public class ArquivoExcelAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;
        if (file == null)
        {
            return false;
        }

        var extension = Path.GetExtension(file.FileName);
        if (extension != ".xls" || extension != ".xlsx") return false;
    }
}

Usage:

[ArquivoExcel(ErrorMessage = "Apenas arquivos do Excel são aceitos.")]
[Display(Name = "Arquivo Excel")]
public HttpPostedFileBase ArquivoExcel { get; set; }
    
15.12.2015 / 20:54