We help IT Professionals succeed at work.

How do i do a regex for file extension and file path form validation to use in javascript

MrFahad
MrFahad asked
on
Medium Priority
1,574 Views
Last Modified: 2012-05-06
Hello,
does anyone know how to make file extension validation regex to use with javascript note: my users upload photo from their harddisk so we need to validate the path

Thank you
Comment
Watch Question

CERTIFIED EXPERT
Commented:
could you please assign more points?
<form onsubmit="return validateHeight(this);">
<input type="text" name="imagename">
<input type="submit" value="validate extension">
</form>
 
 
<script language="javascript">
var pattern=new RegExp("\.(gif|jpg)$");
 
function validateHeight(formObj){
//  alert(pattern.test(formObj.imagename.value));
  return (pattern.test(formObj.imagename.value));
}
</script>

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
What are the allowable extentions? JPG, GIF, PNG, BMP?  I'll assume all of them.

<form action="whatever" onsubmit="return validateExt(this)" enctype="multipart/form-data">
...all your form stuff.
<input type="file" name="file" id="file" />
</form>

//place this between your script tags
function validateExt(formToValidate)
{
  if(!formToValidate.file.value.match(/^.+\.(jpe?g|bmp|png|gif)$/i))
  {
     return false;
  }
  //do whatever else here
  return true;
}
//also test on your server side in case javascript is disabled!

Open in new window

Author

Commented:
i used Morcalavin solution but bot solutions work great
thanks for the help guys :)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.