jquery regex

I need to create a regex to validate file extensions.  The format for the string is the following: index.html or /home/test.htm . I need to make sure only html and htm extensions have been entered
LVL 19
erikTsomikSystem Architect, CF programmer Asked:
Who is Participating?
 
Derek JensenConnect With a Mentor Commented:
Have you tested it?? .*[html|htm] is not checking for an extension. All it's checking for is that the filename ends with h or t or m or l.
It's also superfluous:
([html|htm] == [html])
 !=
(\.(html|htm) == \.html?)

Open in new window

0
 
FinecCommented:
You can try this uploader.

Or other possible solution is check file extension manually:

<script type="text/javascript">

var isValid = false;

$(function () {
    $("input:file").change(function () {
        var fileName = $(this).val();
        isValid = fileName && fileName.match('\.htm(l)?$');
    });
});
</script>

Open in new window

0
 
Julian HansenCommented:
You can try this
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
	$('#select').change(function() {
		var file = $(this).val();
		var match = file.match(/^.*[html|htm]$/);
		alert(match);
	});
});
</script>
</head>
<body>
Input here <input type="file" id="select" />
<div id="result">
</div>
</body>
</html>

Open in new window

0
 
Derek JensenCommented:
Neither one of these regexes will work.

If you're looking for *just* the regex, you can use the code posted by julian, and simply replace
/^.*[html|htm]$/

Open in new window

with
/\.html?$/i

Open in new window

0
 
Julian HansenCommented:
Why do you need to replace anyting - above code works?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.