I'm trying to validate file type so only JPGs or PNGs can be submitted in my form. I've set it so onChange of the image upload field an alert pops up and the 'upload' button is hidden. However I have 5 fields and if I choose a correct filetype in another box the button is then shown even if the wrong filetype is still selected in another field. How can I clear the input field at the same time as triggering the alert if the filetype is wrong?
I've tried this.value = ""; between changing the class and the alert but I'm not sure of the correct syntax to clear the current box
function validate(fName){
splitName = fName.split(".");
fileType = splitName[1];
fileType = fileType.toLowerCase();
if (fileType != 'jpg' && fileType != 'jpeg' && fileType != 'png'){
document.getElementById("uploadbutton").className = "hide";
alert("You must select a .jpg or .png, file.");
}
else {
document.getElementById("uploadbutton").className = "fwdbutton upload";
}
}
<div id="upload">
<h2>If possible, please could you include photographs of the following:</h2>
<p><label for='uploaded_file1'>Current boiler:</label> <input type="file" name="uploaded_file1" id="uploaded_file1" class="uploadfields" accept="image/png, image/jpg, image/jpeg" onChange="validate(this.value)">X</p>
<p><label for='uploaded_file2'>Gas meter:</label> <input type="file" name="uploaded_file2" id="uploaded_file2" class="uploadfields" accept="image/png, image/jpg, image/jpeg" onChange="validate(this.value)">X</p>
<p><label for='uploaded_file3'>Boiler pipe work:</label> <input type="file" name="uploaded_file3" id="uploaded_file3" class="uploadfields" accept="image/png, image/jpg, image/jpeg"onChange="validate(this.value)">X</p>
<p><label for='uploaded_file4'>Outside flue:</label> <input type="file" name="uploaded_file4" id="uploaded_file4" class="uploadfields" accept="image/png, image/jpg, image/jpeg"onChange="validate(this.value)">X</p>
<p><label for='uploaded_file5'>Anything else relevant:</label> <input type="file" name="uploaded_file5" id="uploaded_file5" class="uploadfields" accept="image/png, image/jpg, image/jpeg" onChange="validate(this.value)">X</p><br />
<input class="backbutton showmoved" type="button" value="<< back" /> <input class="fwdbutton upload" id="uploadbutton" type="button" value="upload >>" />
<p><a class="nophotos" id="nophotos">I have no photos >></a></p>
</div>
Many thanks for any advice,
Helen
Please try this.
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function ValidateSingleInput(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
oInput.value = "";
return false;
}
}
}
return true;
}
File 1: <input type="file" name="file1" onchange="ValidateSingleInput(this);" /><br />
File 2: <input type="file" name="file2" onchange="ValidateSingleInput(this);" /><br />
File 3: <input type="file" name="file3" onchange="ValidateSingleInput(this);" /><br />
use a counter to see if you have more errors:
var counter= 0;
function validate(fName){
splitName = fName.split(".");
fileType = splitName[1];
fileType = fileType.toLowerCase();
if (fileType != 'jpg' && fileType != 'jpeg' && fileType != 'png'){
alert("You must select a .jpg or .png, file.");
counter = counter + 1;
}
if (counter !=0){
document.getElementById("uploadbutton").className = "hide";
}else{
document.getElementById("uploadbutton").className = "fwdbutton upload";
}
}
each time you run the function it will check if you have an error. This code otherwise is an example and doesn't handle if you fix a previously marked error.
My advice is to redesign the code to check each input once on button click and trigger the alert of the submission. Instead of doing so that is overcomplicating things. So leave the button always visible and run the function on uploadButton click
Hope this will help you. Initially Upload button is hidden when all the valid files are selected you will see upload button and any invalid type will give you alert.
var isValid = [0];
var sumTotal=0;
function validate(fileNo){
var files = event.target.files;
var filetype = files[0].type;
if (filetype == 'image/jpeg' || filetype == 'image/jpeg' || filetype == 'image/png'){
isValid[fileNo]=1;
}else{
alert("You must select a .jpg or .png, file.");
isValid[fileNo]=0;
}
sumTotal = isValid.reduce(function(a, b) { return a + b; }, 0);
if(sumTotal==5){
document.getElementById("uploadbutton").style.display="block";
}else{
document.getElementById("uploadbutton").style.display="none";
}
}
<div id="upload">
<h2>If possible, please could you include photographs of the following:</h2>
<p><label for='uploaded_file1'>Current boiler:</label> <input type="file" name="uploaded_file1" id="uploaded_file1" class="uploadfields" onChange="validate(1)">X</p>
<p><label for='uploaded_file2'>Gas meter:</label> <input type="file" name="uploaded_file2" id="uploaded_file2" class="uploadfields" onChange="validate(2)">X</p>
<p><label for='uploaded_file3'>Boiler pipe work:</label> <input type="file" name="uploaded_file3" id="uploaded_file3" class="uploadfields" onChange="validate(3)">X</p>
<p><label for='uploaded_file4'>Outside flue:</label> <input type="file" name="uploaded_file4" id="uploaded_file4" class="uploadfields" onChange="validate(4)">X</p>
<p><label for='uploaded_file5'>Anything else relevant:</label> <input type="file" name="uploaded_file5" id="uploaded_file5" class="uploadfields" onChange="validate(5)">X</p><br />
<input class="backbutton showmoved" type="button" value="<< back" /> <input class="fwdbutton upload" style="display: none;" id="uploadbutton" type="button" value="upload >>" />
<p><a class="nophotos" id="nophotos">I have no photos >></a></p>
</div>
You can use the following regular expression to check whether the file valid.
/\.(jpe*g|png)$/gi
And then you can use the test() method to check if the file is valid in your if statement.
if(/\.(jpe?g|png)$/gi.test(s)) {
//TODO
}
Related
On my site I have multi file upload form with fields:
<input name="files[]" type="file" id="files" size="30" />
<input name="files[]" type="file" id="files" size="30" />
<input name="files[]" type="file" id="files" size="30" />
and I want to validate this fields with javascript code, I know how to get value for some simple fields with javascript but I don`t know how to get values from this fields with names "files[]", how javascript see this fields, array or...?
How to apply validation of size and file type using javascript
<!DOCTYPE html>
<html>
<body>
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<button onclick="myFunction()">Get File Name-Type-Size</button>
<script>
function myFunction() {
var input, file;
if (!window.FileReader) {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
var input=document.getElementsByName('files[]');
for(var i=0;i<input.length;i++){
var file = input[i].files[0];
bodyAppend("p", "File " + file.name + " is " + formatBytes(file.size) + " in size"+" & type is "+ fileType(file.name));
}
}
//function to append result to view
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
//function to find size of file in diff UNIT
function formatBytes(bytes,decimals) {
if(bytes == 0) return '0 Byte';
var k = 1000;
var dm = decimals + 1 || 3;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
//function to find file type
function fileType(filename){
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}
</script>
</body>
</html>
Check this now you can put conditions on type of file & size.
// Try this jQuery ;)
$("form").on('change', 'input[type=file]', function() {
var file;
var this = $(this);
if (file = this.files[0])
{
var img = new Image();
img.onload = function () {
// correct
// check alert(img.src)
}
img.onerror = function () {
//error info
};
img.src = _URL.createObjectURL(file);
}
}
<!DOCTYPE html>
<html>
<body>
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<button onclick="myFunction()">Get File Type</button>
<script>
function myFunction() {
var file=document.getElementsByName('files[]');
for(var i=0;i<file.length;i++){
console.log(file[i].value);
}
}
</script>
</body>
</html>
you can get files name like this.
Thanks Bhavik vora But already done with this one
<html>
<head>
<title>client-side image (type/size) upload validation</title>
<meta charset=utf-8>
<style>
</style>
</head>
<body>
<form><fieldset><legend>Image upload</legend>
<input type="file" name="file[]" onchange="getImg(this,100,'jpeg|png')">
<input type="file" name="file[]" onchange="getImg(this,100,'jpeg|png')">
</fieldset>
</form>
<script>
function getImg(input,max,accepted){
var upImg=new Image(),test,size,msg=input.form;
msg=msg.elements[0].children[0];
return input.files?validate():
(upImg.src=input.value,upImg.onerror=upImg.onload=validate);
"author: b.b. Troy III p.a.e";
function validate(){
test=(input.files?input.files[0]:upImg);
size=(test.size||test.fileSize)/1024;
mime=(test.type||test.mimeType);
mime.match(RegExp(accepted,'i'))?
size>max?(input.form.reset(),msg.innerHTML=max+"KB Exceeded!"):
msg.innerHTML="Upload ready...":
(input.form.reset(),msg.innerHTML=accepted+" file type(s) only!")
}
}
</script>
</body>
</html>
I have a register form with 2 fields includes random int and a result input field for the answer
there's a Javascript code to check fields are not empty when submitting
I'm trying also to calculate the 2 fields and compare it with the result value
Here's the HTML :
<form method="post" id="contactForm" enctype="multipart/form-data" name="q_sign">
<input type="text" name="q_name" id="senderName"/>
<input type="text" name="q_mail" id="senderEmail" />
<input name="val1" type="text" disabled id="val1" value="php random value1" readonly="readonly" />
<input name="val2" type="text" disabled id="val2" value="php random value2" readonly="readonly" />
<input type="text" name="total" id="total" />
<input type="submit" id="sendMessage" name="sendMessage" value="Register" onClick="return check_data(this.form)" />
Javascript part :
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if(document.q_sign.q_name.value==''){
alert("please enter your name");
return false;
}else if(document.q_sign.q_mail.value==''){
alert("please enter your email");
return false;
}else if(document.q_sign.total.value!=(val1+val2)){ //Issue is here
alert("wrong answer");
return false;
}else{
return true;
}}
maybe this is your expect below
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if (document.q_sign.total.value != (eval(val1) + eval(val2))) {
alert("wrong answer");
return false;
} else {
return true;
}
}
In my code I want to accept only image file.otherwise it will not accept and will give alert that its not image file.
I have done below code in jsfiddle:--
jsfiddle link
but the problem is it..It is not giving any message.what am I doing wrong?
https://jsfiddle.net/weufx7dy/2/
You forgot to add id on file element
<input type="file" id="file" name="fileUpload" size="50" />
You had used
var image =document.getElementById("file").value;
but forgot to give id to file control so give that
<input type="file" name="fileUpload" id="file" size="50" />
and try following code in w3schools tryit browser and use onClick event on submit button instead of onSubmit
<!DOCTYPE html>
<html>
<body>
<div align="center">
<form:form modelAttribute="profilePic" method="POST"enctype="multipart/form-data" action="/SpringMvc/addImage">
<input type="file" name="fileUpload" id="file" size="50" />
<input type="submit" value="Add Picture" onClick="Validate();"/>
</form:form>
</div>
<script>
function Validate(){
var image =document.getElementById("file").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.gif|\.GIF|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg,.gif");
document.getElementById("file").focus();
return false;
}
}
return true;
}
</script>
</body>
</html>
Use this :
userfile.addEventListener('change', checkFileimg, false);
function checkFileimg(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if (!(sFileExtension === "jpg")) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Please make sure your file is in jpg format.\n\n";
alert(txt);
document.getElementById('userfile').value='';
}
}
}
I´m working in a payment gateway where the user Name the Price for my digital books. An input box (to text the price) and a "Pay now" button are displayed. BUT:
If the price is less than 0.50 the payment button disapear and the download button appear
If the user introduce a "," instead a "." a box is displayed (please, enter a valid number)
Here is the form with the input box:
<form id="hikashop_paypal_form" name="hikashop_paypal_form" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="business" value="X" />
<input type="hidden" name="item_name_1" value="X" />
<input id="amount_1" name="amount_1" class="amount_1"/></form>
Pay Now button (it should be hiden if 1 is true)
<div id="PayNow" class="PayNow">
<input id="PayNow_button" type="submit" class="btn btn-primary" value="Pay now" name="" />
</div>
Download Now Button (it should be shown if 1 is true)
<div id="downloadNow" class="downloadNow">
Download now
</div>
Info box (It should be shown if 2 is true)
<div id="info" class="info">
Enter a valid number
</div>
And the question is: How can I do it?
I supose the solution passes by using javascript, but I don´t know how exactly... Thanks for you time...
I don´t know how, but it works for me:
Try it here: IBIZA! Book Download
<form id="pplaunch" action="https://www.paypal.com/cgi-bin/webscr" method="POST">
<input type="hidden" name="cmd" value="_xclick">
<input id="issueid" name="issueid" type="hidden" value="ARCHIVE NAME">
<input type="hidden" id="currency" name="currency" value="EUR">
<input type="hidden" name="business" value="YOUR PAYPAL ID" />
<input type="hidden" value="0" name="test_ipn"></input>
<input type="hidden" name="item_name" value="PRODUC NAME">
<input type="hidden" value="1" name="no_shipping"></input>
<input type="hidden" value="0" name="no_note"></input>
<input type="hidden" value="utf-8" name="charset"></input>
<input type="hidden" value="Super" name="first_name"></input>
<input type="hidden" value="http://www.YOURWEBSITE.com/return" name="return"></input>
<input type="hidden" value="http://www.OURWEBSITE.com/cancel" name="cancel_return"></input>
<div class="nameprice" style="float:left;margin-right:15px;>
<span style="font-size:small;">Name your price: </span><input id="amount" name="amount" size="6" maxlength="5" type="text"> <span style="font-size:small;color:#ccc;">From 0.00€</span>
</div>
<div id="pricerror"></div>
<div class="buttonspace">
<button id="buybutton" class="buybutton" type="button">Checkout</button>
<div id="descargaGratisMensaje"></div>
<div style="display: block;" class="pay">
</div>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
function newPopup(url, width, height){
popupWindow = window.open(url,'_blank','height='+height+',width='+width+',left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes');
return false;
}
function displaybutton(displayclass){
if(displayclass == 'pay'){
$('.pay').css('display','block');
$('#pplaunch').attr('action', 'https://www.paypal.com/cgi-binwebscr');
$('#buybutton').html('Pagar');
}else{
$('.pay').css('display','none');
$('#pplaunch').attr('action', 'http://www.example.com/archive/'+$('#issueid').val());
$('#buybutton').html('Descargar');
$('#descargaGratisMensaje').html('Un Me Gusta podría ser un buen intercambio');
}
}
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n) && (n.search(/0x/i)<0);
}
function price(n){
// return null if n is not a price, or n rounded to 2 dec. places
if(!isNumber(n)){
// maybe the user entered a comma as a decimal separator
n = n.replace(/,/g,'.');
if(!isNumber(n)){
return null;
}
}
// now we know it is a number, round it up to 2 dec. places
return Math.round(parseFloat(n)*100)/100;
}
function pricecheck(){
var data = $.trim($('#amount').val());
var myprice = price(data);
if(myprice == null){
if(data == ''){
$('#pricerror').html('');
}else{
$('#pricerror').html('Please enter a price.');
}
displaybutton('pay');
return false;
}
if(myprice == 0){
$('#pricerror').html('');
displaybutton('nopay');
}else if(myprice < 0.5){
$('#pricerror').html('The minimum price is '+currencysymbol+'0.50.
Please enter either zero, or at least '+currencysymbol+'0.50.');
displaybutton('pay');
}else{
$('#pricerror').html('');
displaybutton('pay');
}
jQuery('.content').hide();
}
var currencysymbol = '$';
$.getScript('//www.geoplugin.ne/javascript.gp?ref=panelsyndicate.com', function() {
if(geoplugin_continentCode() != 'EU'){return;}
$('#currency').val('EUR');
currencysymbol = '€';
$('.currencysymbol').html(currencysymbol);
});
$(document).ready(function(){
var dialog = $('#modal').dialog({
title: 'IBIZA!'
, autoOpen: false
, closeText: ''
, modal: true
, resizable: false
, width: 500
});
$('#buybutton').click(function() {
$('#pplaunch').submit();
});
$('#pplaunch').submit(function() {
var myprice = price($.trim($('#amount').val()));
if((myprice != 0) && ((myprice == null) || (myprice < 0.5))){
$('#pricerror').html('Please enter your price.');
$('#amount').focus();
return false;
}
});
$('.modaltrigger').click(function() {
var issueid = $(this).attr('href').substr(1);
$('#issueid').val(issueid); // Comic ID
$('#include_a_message_to').html(issues[issueid].include_a_message_to); // Destinee of the message
dialog.dialog('option', 'title', issues[issueid].title); // Title of the comic
$('#issuelangs').html(issues[issueid].langs); // Languages in which the comic is available
dialog.dialog('option', 'position', { my: "center", at: "center", of: window });
dialog.dialog('open');
// prevent the default action, e.g., following a link
pricecheck();
return false;
});
$('#amount').bind('input propertychange', function() {
pricecheck();
});
$('.custommsg').hide();
$('.msgtrigger').click(function() {
var cmsg = $('.custommsg');
if(cmsg.is(':visible')){
cmsg.hide();
$('.sendmsg').show();
}else{
$('.sendmsg').hide();
cmsg.show();
$('.msgtxt').focus();
}
return false;
});
$('.msgtxt').keyup(function(){
if($(this).val().length > maxlength){
$(this).val($(this).val().substr(0, maxlength));
}
var remaining = maxlength - $(this).val().length;
$('#msgtxtnumcharsleft').text(remaining);
});
var maxlength = 200;
var remaining = maxlength - $('.msgtxt').val().length;
$('#msgtxtnumcharsleft').text(remaining);
});
</script>
I am new to .asp and Javascript and wondered if someone was able to advise how to show validation errors for fields below the form in a single table or text field rather than using alerts. Alerts and validation are working.
Here is the table that i plan to put the validation errors into:
<asp:Table ID="StatusTable"
runat="server" Width="100%"><asp:TableRow ID="StatusRow" runat="server">
<asp:TableCell ID="StatusTextCell" runat="server" Width="95%">
<asp:TextBox ID="StatusTextBox" runat="server" Width="100%" />
</asp:TableCell><asp:TableCell ID="StatusPadCell" runat="server" Width="5%">
</asp:TableCell></asp:TableRow></asp:Table>
And here is an example of some the Javascript I am using where i need the validation error messages to show in the table rather than from alerts.
Would be extremely grateful for any advise
< script type = "text/javascript"
language = "Javascript" >
function RequiredTextValidate() {
//check all required fields from Completed Table are returned
if (document.getElementById("<%=CompletedByTextBox.ClientID%>").value == "") {
alert("Completed by field cannot be blank");
return false;
}
if (document.getElementById("<%=CompletedExtTextBox.ClientID %>").value == "") {
alert("Completed By Extension field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNoTextBox.ClientID %>").value == "") {
alert("Employee No field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNameTextBox.ClientID %>").value == "") {
alert("Employee Name field cannot be blank");
return false;
}
return true;
}
< /script>
function ValidateFields() {
//Validate all Required Fields on Form
if (RequiredTextValidate() && CheckDate(document.getElementById("<%=SickDateTextBox.ClientID%>").value) && CheckTime(this) && ReasonAbsent() && ReturnDateChanged() && FirstDateChanged() && ActualDateChanged() == true) {
return true;
}
else
return false;
}
There are many ways that this type of thing can be done, here is one way which I have put together based on what you have so far...
http://jsfiddle.net/c0nh2rke/
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
HTML
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
Script
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
The best JavaScript is no JavaScript.
To that end, consider:
<form action="javascript:alert('Submitted!');" method="post">
<input type="text" name="someinput" placeholder="Type something!" required />
<input type="submit" value="Submit form" />
</form>
Notice how the browser will render native UI to show that the field was left blank? This is by far the best way to do it because it doesn't rely on JavaScript. Not that there's anything wrong with JS, mind, but far too often a single typo in form validation code has caused hours of debugging!