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

Asked

Viewed 425 times

2

I am importing an excel file using Asp.net and validate to see if it is really an excel or not. I don’t want to use if and else, so I’m trying to do this through Annotations.

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

Does anyone know if it is really possible to do this validation on Asp.net with these reg. Expressions?

Follow 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; }
  • Hello @joaoigor welcome to Sopt. Take a look at this link right here from Sopt http://answall.com/questions/5115/comor- restricted-determinadas-extens%C3%B5es-de-files-and-save-in-database, I believe it’s related to what you’re looking for.

  • 1

    Please note that the fact that the file has the Excel extension does not mean that it is a valid Excel file. Similarly, you may have an Excel file with a different extension (example, .xyz) and remains a valid Excel file.

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;
    }
}

Use:

[ArquivoExcel(ErrorMessage = "Apenas arquivos do Excel são aceitos.")]
[Display(Name = "Arquivo Excel")]
public HttpPostedFileBase ArquivoExcel { get; set; }
  • Will this Arquivoexcelattribute class be created inside my model? if yes, this Path.Getextension will not work because the path only exists in the controller.

  • No, you create a directory Attributes in its solution and implements there a new class. Path.GetExtension may exist in that class yes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.