This could work out for you
var str = 'D:/test.xml';
var str2 = 'D:\\folder\\test.xml';
var str3 = 'D:/folder/test.xml';
var str4 = 'D:\\folder/test.xml';
var str5 = 'D:\\test\\test\\test\\test.xml';
var regex = new RegExp('^[a-z]:((\\\\|\/)[a-zA-Z0-9_ \-]+)+\.xml$', 'i');
regex.test(str5);
The reason of having \\\\
in RegExp to match a \\
in string is that javascript uses \
to escape special characters, i.e., \n
for new lines, \b
for word boundary etc. So to use a literal \
, use \\
. It also allows you to have different rules for file name and folder name.
Update
[a-zA-Z0-9_\-]+
this section of regexp actually match file/folder name. So to allow more characters in file/folder name, just add them to this class, e.g., to allow a *
in file/folder name make it [a-zA-Z0-9_\-\*]+
Update 2
For adding to the answer, following is an RegExp that adds another check to the validation, i.e., it checks for mixing of /
and \\
in the path.
var str6 = 'D:/This is folder/test @ file.xml';
var str7 = 'D:/This is invalid\\path.xml'
var regex2 = new RegExp('^[a-z]:(\/|\\\\)([a-zA-Z0-9_ \-]+\\1)*[a-zA-Z0-9_ @\-]+\.xml?', 'gi');
regex2
will match all paths but str7
Update
My apologies for mistyping a ?
instead of $
in regex2
. Below is the corrected and intended version
var regex2 = new RegExp('^[a-z]:(\/|\\\\)([a-zA-Z0-9_ \-]+\\1)*[a-zA-Z0-9_ @\-]+\.xml$', 'i');