I have the form having the follwing fields,
<form onsubmit="return checkcreateform()" action="/gallery/create" method="post" enctype="multipart/form-data">
<label>Type:*</label>
<label for="type-1">
<input type="radio" checked="checked" value="1" id="type-1" name="type">Image
</label>
<br>
<label for="type-2">
<input type="radio" value="2" id="type-2" name="type">Video
</label>
<label class="itemdetailfloatL required" for="file">File:*</label>
<input type="hidden" id="MAX_FILE_SIZE" value="8388608" name="MAX_FILE_SIZE">
<input type="file" tabindex="5" class="text-size text" id="file" name="file">
<input type="submit" value="Create" id="submit" name="submit">
</form>
I want to validate before form submit. Here how can i validate if user select type as Image and upload video or select type as video and upload image ?
We can achieve this by javascript or jquery.Any quick way to validate this ?
Kindly help me on this.
Instead of using
onsubmit
, use jQuery's submit handler, and validate using some javascript like the following:jsFiddle version here, tested in IE8, RockMelt (based on Chrome) and Firefox 7: http://jsfiddle.net/Ngrbj/4/
Using files property on input:file you can loop through file objects and check type property
The answer provided works, but something that will run a little faster with a lot fewer lines for the validation code, using javascript array functions:
Then, the if statement in the submit code is just swapped with:
Every File type has a 'type' property, for example: 'image/jpeg', 'audio/mp3' and so on...
This is an example for one way to check the type of the file by using the 'match' method (of strings):
You can also write it the boolean way:
First you should change your html like this:
Then, you need a function like this:
you can try this:
You can use this function in your
checkcreateform()