user5483305
user5483305

Reputation:

File name validation with extension

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

Answers (2)

mikeyq6
mikeyq6

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

empiric
empiric

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

  • any word character (same as [a-zA-Z0-9_])
  • the hyphen -

Updated Code:

var filename = 'index.html';

if (filename.match(/^([\w\-]+)\.html$/)) {
  alert('Success: valid');
} else {
  alert('Error: invalid');
}

Demo of the regex

Updated jsFiddle

Upvotes: 0

Related Questions