Search code examples
c#regexasp.net-core-mvcentity-framework-coredata-annotations

RegEx for specific extension validation


I'm trying to validate upload file extensions on client side (razor) with DataAnnotations, however it looks like no matter what file I'm uploading I always get the "Error Message",

 [RegularExpression(@"^.*\.(jpg | JPG | gif | docx | doc | DOC | pdf | PDF)$",
           ErrorMessage = "bla bla")]
        public IFormFile MyImage { get; set; }

My code is as follows:

 <input name="MyImage" class="input-validation-error" id="MyImage" aria-invalid="true" aria-describedby="MyImage-error" type="file" data-val="true" data-val-regex-pattern="^.*\.(jpg | JPG | gif | docx | doc | DOC | pdf | PDF)$" data-val-regex="bla bla">

Solution

  • Your original expression works fine and let's just slightly simplify it using an i flag:

    (.*\.)(jpe?g|gif|docx?|pdf)$
    

    DEMO

    TEST

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
        public static void Main()
        {
            string pattern = @"(.*\.)(jpe?g|gif|docx?|pdf)$";
            string input = @"any_file_name_we_wish_here_with_!@#$%^&*_1234567.jpg
    any_file_name_we_wish_here_with_!@#$%^&*_1234567.jpeg
    any_file_name_we_wish_here_with_!@#$%^&*_1234567.JPG
    any_file_name_we_wish_here_with_!@#$%^&*_1234567.docx
    any_file_name_we_wish_here_with_!@#$%^&*_1234567.doc
    any_file_name_we_wish_here_with_!@#$%^&*_1234567.pdf
    any_file_name_we_wish_here_with_!@#$%^&*_1234567.gif
    any_file_name_we_wish_here_with_!@#$%^&*_1234567.mp3
    any_file_name_we_wish_here_with_!@#$%^&*_1234567.mp4";
            RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase;
    
            foreach (Match m in Regex.Matches(input, pattern, options))
            {
                Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
            }
        }
    }
    

    RegEx Circuit

    jex.im visualizes regular expressions:

    enter image description here