Reputation:
I am trying to validate a file name in javascript.
The characters that I want to allow are: any letters, any numbers, underscores and hyphens.
I want to alert the user if this condition is not met. I thought I had a regex that would do the job based on some online regex testers, but it isn't working.
Demo https://jsfiddle.net/8g65yuu6/
var filename = 'index.html';
if (filename.match(/^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.html$/)) {
alert('Success: valid');
} else {
alert('Error: invalid');
}
I was hoping this would validate a html file, the condition is never met.
Upvotes: 2
Views: 1933
Reputation: 1148
This would work, and is a lot simpler:
var filename = 'index.html';
if (filename.match(/^([\w\-]+)\.html$/)) {
alert('Success: valid');
} else {
alert('Error: invalid');
}
Not sure why you have the 2 separate clauses:
(?:[\w]\:|\\)
and
(\\[a-z_\-\s0-9\.]+)
Also, the +
after the last clause will always cause it to fail
Upvotes: 2
Reputation: 7878
If you just want to check if the filename contains valid characters no matter their order you can simplify your regex to:
/^([\w\-]+)\.html$/
Explanation: Captures one ore more characters which are
[a-zA-Z0-9_]
)-
Updated Code:
var filename = 'index.html';
if (filename.match(/^([\w\-]+)\.html$/)) {
alert('Success: valid');
} else {
alert('Error: invalid');
}
Upvotes: 0