ASP.net MVC regular expression in view model for filename validation

I've read a few questions that answer this, and I understand the regular expression I'm required to use, however actually applying it in MVC is where I stumble. I will also preface by saying I am terrible at regular expressions so far.

I'm writing a file upload application in MVC and I want to apply standard windows filename validation. \/:*?"<>| are invalid characters anywhere in the name.

My View Model for this is setup like so, using a different regex I found:

    public class FileRenameModel
{
    [RegularExpression(@"^[\w\-. ]+$", ErrorMessage="A filename cannot contain \\ / : * ? \" < > |")]
    [Required]
    public string Filename { get; set; }
    [Required]
    public int FileID      { get; set; }
}

Whenever I try to change the regex to @"^[\\/:?"<>|]+$ the " in the middle kills it and throws an error. I haven't figured out how to properly escape it so that I can include it in the string. When I use the regex without the " it tells me any string I put into the textbox fails. Am I using the ^ incorrectly?

Answers


Use double "" to escape quotes after starting a string with @.

To search for anything except you'd want to insert an additional ^ inside the brackets to create an except for match: @"^[^\\/:?""<>|]+$" Keep the ^ at the beginning as well to match the start of line.

Having said that, keep in mind for validation that browsers handle file names differently. Some older browsers sent a path along with the filename, that might break your validation for a legitimate file.


Need Your Help

No resource found that matches the given name: attr 'android:windowTranslucentNavigation'

android android-4.4-kitkat navigationbar

I'm trying to make the Navigation Bar transparent on devices with 4.4. However, the SDK does not find the resource.

Get the next element by selecting element with a class

javascript jquery

I have a live search and a list element is given a class of hover I am then trying to get the next li element after the hover class upon pressing the down arrow and adding the hover class to that