Windows Path Validation Regular Expression

Windows file system paths use backslashes as separators and start with a drive letter followed by a colon. Path components cannot contain certain reserved characters: \ / : * ? " < > |. This regex validates Windows path formats according to Windows file naming conventions. For Unix/Linux paths, see the Unix path validation article.

Recommended Solution

^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$

Explanation

  • ^ - Start of the string.
  • [a-zA-Z] - Drive letter (A-Z, case-insensitive).
  • : - Colon after drive letter.
  • \\ - Backslash (escaped in regex).
  • (?:[^\\/:*?"<>|\r\n]+\\)* - Zero or more directory names:
    • [^\\/:*?"<>|\r\n]+ - One or more valid characters (excluding reserved characters).
    • \\ - Followed by a backslash.
  • [^\\/:*?"<>|\r\n]* - Optional file or final directory name (no trailing backslash required).
  • $ - End of the string.

Notes

  • This regex validates the format of Windows paths but does NOT verify if the path exists on the filesystem.
  • Reserved characters that cannot appear in file/folder names: \ / : * ? " < > |
  • This pattern does not validate UNC paths (network paths like \\\\server\\share). Modify the pattern to support UNC if needed.
  • Windows has reserved file names (CON, PRN, AUX, NUL, COM1-9, LPT1-9) which are not validated by this regex.
  • Maximum path length in Windows is typically 260 characters (MAX_PATH), but this is not enforced by this regex.
  • Spaces are allowed in path components, which is common in Windows paths (e.g., "Program Files").
  • This pattern requires backslashes. Paths with forward slashes (sometimes accepted by Windows APIs) will not match.
  • For more robust path validation, use filesystem APIs like System.IO.Path in .NET or similar in other languages.

Implementation

const windowsPathRegex = /^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$/;
const isValidWindowsPath = (path) => windowsPathRegex.test(path);

Test Cases

PathTypeValid
C:\\Root directory
C:\\Windows\\System32Absolute path
D:\\Users\\Documents\\file.txtFile path
E:\\Program Files\\ApplicationPath with spaces
F:\\folder\\subfolder\\Trailing backslash
Z:\\dataZ drive
C:\\path-with-dashes\\file_name.extDashes and underscores
C:\\WindowsSimple path
C:\\Users\\admin\\Desktop\\file.docxDocument path
/unix/style/pathUnix path
C:/forward/slashForward slashes
C:\\invalid*nameContains asterisk
C:\\invalid?nameContains question mark
C:\\invalid<>nameContains angle brackets
C:\\invalid|nameContains pipe
C:\\invalid:nameContains colon
invalid\\pathMissing drive letter
(empty string)Empty string
C:Drive letter only
1:\\pathInvalid drive letter