RegEx for specific extension validation

asp.net-core-mvc c# data-annotations entity-framework-core regex

Question

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">
1
0
6/17/2019 2:41:48 PM

Accepted Answer

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

2
5/28/2019 5:04:47 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow