Regular expression for valid filename

Viewed 106989

I already gone through some question in StackOverflow regarding this but nothing helped much in my case.

I want to restrict the user to provide a filename that should contain only alphanumeric characters, -, _, . and space.

I'm not good in regular expressions and so far I came up with this ^[a-zA-Z0-9.-_]$. Can somebody help me?

11 Answers

For full character set (Unicode) use ^[\p{L}0-9_\-.~]+$

or perhaps ^[\p{L}\p{N}_\-.~]+$ would be more accurate if we are talking about Unicode.

I added a '~' simply because I have some files using that character.

When used in HTML5 via pattern:

<form action="" method="POST">
  <fieldset>
    <legend>Export Configuration</legend>
    <label for="file-name">File Name</label>
    <input type="text" required pattern="^[\w\-. ]+$" id="file-name" name="file_name"/>
  </fieldset>
  <button type="submit">Export Settings</button>
</form>

This will validate against all valid file names. You can remove required to prevent the native HTML5 validation.

Related