I have:
<input type="file" />
in my site with a submit button,
How can I validate that this is a .jpg file?
Thanks!
I have:
<input type="file" />
in my site with a submit button,
How can I validate that this is a .jpg file?
Thanks!
Add this to the <head> part of your document:
And then add an ID attribute to your file tag, and on your submit button, add:Code:<script type="text/javascript"> function checkJPG(id){ var el = document.getElementById(id); var patterna = /jpg$/i; var patternb = /jpeg$/i; if(!(patterna.test(el.value) || patternb.test(el.value))){ alert("Your photo format is not a JPEG."); } }; </script>
(Change the highlighted)Code:onclick="checkJPG('id');"
Good luck.
Jeremy | jfein.net
lord22 (11-07-2009)
My version:
Code:function valJpg(file){ if(!/\.jpe{0,1}g$/i.test(file.value)){ alert('.jpg Images Only Please.'); var newFile = document.createElement('input'); newFile.type = 'file'; newFile.onchange = file.onchange; file.parentNode.replaceChild(newFile, file); } }You may need to include other attributes of your original file input if it has them, example:HTML Code:<input type="file" onchange="valJpg(this);">
Which would be required for form submission, etc.Code:function valJpg(file){ if(!/\.jpe{0,1}g$/i.test(file.value)){ alert('.jpg Images Only Please.'); var newFile = document.createElement('input'); newFile.type = 'file';newFile.name = file.name;newFile.onchange = file.onchange; file.parentNode.replaceChild(newFile, file); } }
- John________________________
Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate
lord22 (11-07-2009)
Thank you both![]()
I came up with another version which would preserve the idiosyncratic ways that input fields behave in various browsers, which may or may not be desirable, and also eliminates the need to add in various characteristics of the file input into the function:
Code:function valJpg(file){ if(!/\.jpe{0,1}g$/i.test(file.value)){ alert('.jpg Images Only Please.'); file.parentNode.replaceChild(valJpg.file.cloneNode(true), file); } }HTML Code:<input id="myFile" type="file" onchange="valJpg(this);"> <script type="text/javascript"> valJpg.file = document.getElementById('myFile').cloneNode(true); </script>
- John________________________
Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate
Bookmarks