PDA

View Full Version : validate JPG



lord22
11-07-2009, 05:41 PM
I have:
<input type="file" />
in my site with a submit button,
How can I validate that this is a .jpg file?

Thanks!

Nile
11-07-2009, 07:11 PM
Add this to the <head> part of your document:

<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>

And then add an ID attribute to your file tag, and on your submit button, add:


onclick="checkJPG('id');"

(Change the highlighted)

Good luck.

jscheuer1
11-07-2009, 07:35 PM
My version:


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);
}
}


<input type="file" onchange="valJpg(this);">

You may need to include other attributes of your original file input if it has them, example:


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);
}
}

Which would be required for form submission, etc.

lord22
11-07-2009, 09:30 PM
Thank you both :)

jscheuer1
11-07-2009, 09:54 PM
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:


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);
}
}


<input id="myFile" type="file" onchange="valJpg(this);">
<script type="text/javascript">
valJpg.file = document.getElementById('myFile').cloneNode(true);
</script>