1

I am trying to validate a file name with invalid characters in the file name without validating file path. I have tried various combinations but none of my javascript functions seem to do the trick.

 @Html.TextBoxFor(model => model.Attachment, new { type = "file" , onchange = "ValidateFileName(this)" })

JS:

function ValidateFileName(name) {
        if (name.value.match(/\.\.[a-z][a-z][a-z]$/) || name.value.match(/\.\.[a-z][a-z][a-z][a-z]$/) || name.value.match(/^(?!\.)(?!com[0-9]$)(?!con$)(?!lpt[0-9]$)(?!nul$)(?!prn$)[^\|\*\?\\:%<>/$"]*[^\.\|\*\?\\:%<>/$"]+$/)) {

            alert('Invalid file extension.');
            name.form.reset();
            name.focus();
            return false;
        }
    }
user7221204
  • 99
  • 3
  • 12

2 Answers2

2

This is the regular expression I normally use to validate Windows file names:

^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\";|/]+$

but if your name variable includes the file path, you first have to extract the file name out of it using:

var filename = name.split(/(\\|\/)/g).pop();

or:

var name_pieces = name.split('\\');
var filename = name_pieces[name_pieces.length - 1];

On a side note, double check the behavior of this part of your code:

onchange = "ValidateFileName(this)"

because I feel there is something wrong undergoing... I don't know, but something keep on telling me it should be written as:

onchange = "ValidateFileName(this.value)"
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
  • Splitting the path from the file name was what I was missing. Thank you ! It works now. Also answering your question about this.value , since my JS function actually checks with parameter.value I was not passing in this.value. – user7221204 Dec 17 '17 at 03:48
0

In .NET, you can use the Path.GetInvalidFileNameChars() static method to get a list of invalid characters. (Note: There's also Path.GetInvalidPathChar() for file path characters, which are different).

On the server-side, you can do this:

var invalidChars = Path.GetInvalidFileNameChars();
var hasBadChars = filename.Any(c =>  invalidChars.Contains(c));

For the JS side, you could output the invalidChars into an JS array server-side, then do something like this:

if (invalidChars.some(function(v) { return filename.indexOf(v) >= 0; })) {
    // There's at least one
}
John M. Wright
  • 4,477
  • 1
  • 43
  • 61
  • I understood the server side of it. But could you tell me how to implement the JS part. i am just looking to reset the file field and show an alert that there are invalid chars. – user7221204 Dec 17 '17 at 03:50