JavaScript - Filename Validation For Input Type File
Hello all,
I have in my application input type file for uploading files. How can i do javascript validation to check if filename has special characters in it?? Thanks Similar TutorialsHowdy I have a <input type="File"> in my html, I need it because the user can select a jpg image and when they click submit it will post that image to a webservice. My question... Is their a way to load the file they selected so that I can draw it on a canvas? Sounds simple but I cannot figure it out! Thanks in advance Eckythump I am wanting to enable a file to be uploaded and attached to an email form. I however wish to only limit this to picture files with a size no larger than 1MB. Is there a way to do this with javaScript. My Html code: Code: <!-- Add a picture file --> <tr><td align="left">Upload your favourite Yorkie photo for the Picture of the Month.<br /> <input type="file" name="upload" accept="image/gif" size="30" style="margin-left: 15px; margin-top:5px; color: #0000; background-color: #00FF77;" /></td></tr> Just need to know if this can be validated with javascript to ensure the conditions are as per above. I need to change input type="text" to input type="password" via JavaScript Code: <form id="login" action="#" method="post"> <input id="username-field" type="text" name="username" title="Username" onmousedown="javascript:this.value=''; javascript:this.focus();" value="Username" tabindex="1" /> <input id="password-field" type="text" name="password" title="Password" onmousedown="javascript:this.value=''; javascript:this.type='password'; javascript:this.focus();" value="Password" tabindex="2" /> <input type="submit" name="submit" value="sign in" tabindex="3" /> </form> This works in Firefox and Safari but not IE So then I tried this code Code: <script type="text/javascript"> function passit(ip){ var np=ip.cloneNode(true); np.type='password'; if(np.value!=ip.value) np.value=ip.value; ip.parentNode.replaceChild(np,ip); } </script> <form id="login" action="#" method="post"> <input id="username-field" type="text" name="username" title="Username" onmousedown="javascript:this.value=''; javascript:this.focus();" value="Username" tabindex="1" /> <input id="password-field" type="text" name="password" title="Password" onmousedown="javascript:this.value=''; passit(this.form[0]); javascript:this.focus();" value="Password" tabindex="2" /> <input type="submit" name="submit" value="sign in" tabindex="3" /> </form> This does what I need but turns the username type to password field not the password box Please can somone help! This was climbing up the tree strructure, where on top and only on very top is one input of type text Now I inserted (inside tree) some inputs of type hidden , which needs to be ignored while below while operates. How to do that ? Getting nowhere with this. Code: function doit(tmpObj) { while (!tmpObj.getElementsByTagName('input')[0]) { tmpObj.style.visibility = 'hidden'; tmpObj = tmpObj.parentNode; } ... hello, I have a form which contains multiple inputs with type 'text' and 'radio' buttons, and i'm trying to validate all these fields using javascript. Know that the id's and names came from database. so i want to validate by type. Please anyone help me as fast as possible thank you Newbie here. I could not find the syntax how to set initial value he Code: var indat = window.clipboardData.getData ("Text"); . . . . . <input type="text" name="q" value="xxxxxx" size="40" /> I would like the value to be the indat var value I saw lot of samples with value="xxxxx" (hard coded value) but could not find sample for var value thanks for help !! I have an input element of type=text. It has a fixed width, but I want to expand that width as the user is typing if the text doesn't fit inside. I did something similar to this with <textarea> and the vertical height. PHP Code: // javascript in mootools textarea.addEvent('keyup', function(){ textarea.setStyle('height', this.getScrollSize().y ); }); Does anyone know of a way to do this with <input type='text'>? I have a page with a customizable background. The user can choose a picture to set as the background by finding the picture file they want after clicking the upload input. The path of the file they select is saved into a cookie, and the page then switches backgrounds. This all works perfectly, but the value that the upload input returns is only the file name, not the full path. For example, let's say I wanted to choose a picture named "bg.jpg" in the "Windows" folder of the C drive. The full path would be "C:/Windows/bg.jpg". However, the value that the input returns is just "bg.jpg". How would I have the input return the entire path of the file using JavaScript? This has been bothering me for a while...any help would be much appreciated. <script type="text/javascript"> function showhide(divid) { thediv = document.getElementById(divid); if(thediv.style.display == 'none' || thediv.checked=='true' ){ thediv.style.display='block' }else{ thediv.style.display='none' } } </script> This part its working: <input type=checkbox name=type value='1' onclick="return showhide('div1');">Submit - 1 <input type=checkbox name=type value='2' onclick="return showhide('div2');">Submit - 2 This part its not working <input type=checkbox name=type value='1' checked="checked" onclick="return showhide('div1');">Submit - 1 <input type=checkbox name=type value='2' onclick="return showhide('div2');">Submit - 2 how i can make if its already check input value 1 to show div1 but if i remove the checked to dont show anymore div1 thanks Below is a script I found at http://bytes.com/topic/javascript/an...cookie-problem The idea is a like button, like on fb, in a form which updates a db field I can use to display the number of likes, and my goal is to disable the like button for the rest of the session, or a day, or whatever. This script disables it onclick, the problem is I can't figure out how to get it to submit the form as well. I have found it does submit if the input type is 'submit', but then it doesn't call the disable function. I tried writing another function to submit the form but no go. Code: <html> <head> <title>Vote Button</title> <script type="text/javascript"> function checkForVote() { // If there is a cookie... if(document.cookie != "") { if(getCookie("voted") == 1) { // Disable the button again if user already voted. disableButton(); } } } function disableButton() { var submitvote = document.getElementById("submitvote"); submitvote.disabled = true; submitvote.value = "You Already Voted."; } function setCookie(name, value, days) { if(days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires = " + date.toGMTString(); } else { var expires = ""; } document.cookie = name + "=" + value + expires + "; path=/"; // Disable the button as soon as the user clicks it. disableButton(); } function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') { c = c.substring(1,c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length,c.length); } } return null; } </script> </head> <body> <form name="voteform" id="voteform" action="foo.php" method="post"> <input type="button" name="submitvote" id="submitvote" onclick="setCookie('voted', 1, -1);" value="Submit Vote"/> </form> </body> <script type="text/javascript"> // Run checkForVote() at end of document so that form and contents can be referenced window.onload = checkForVote(); </script> </html> In fact: does input type=image belong to the form's elements collection, in ECMAScript ? It looks like not. When traversing the form's elements collection with classical javascript (document.forms[formname].elements), an input type="image" is not included. Is this an inheritance from old browsers interpretors? Does anyone know the reason for this omission? hi guyz i do have a problem in passing javascript variable to <input type=hidden value=""> here's my code: <?php while ($row = mysql_fetch_array($result)) { ?> <script type="text/javascript"> function viewcodec(){ var randomValueCodec = randomString(5, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'); document.getElementById('commentMarkCodeCompCodec-'+<?php echo $row['p_id'];?>).innerHTML = randomValueCodec; document.getElementById('commentMarkCodeComp-'+<?php echo $row['p_id'];?>).innerHTML = randomValueCodec; } </script> <form action="" method="post" name="postsForms"> <div class="commentBox" align="right" id="commentBox-<?php echo $row['p_id'];?>" <?php echo (($comment_num_row) ? '' :'style="display:none"')?>> <input type=text id="commentMarkname-<?php echo $row['p_id'];?>" name="commentmarkname" class="commentMarkname" size="35" maxlength="20"> <textarea class="commentMark" id="commentMark-<?php echo $row['p_id'];?>" name="commentmark" cols="60"></textarea> <input type=text id="commentMarkcode-<?php echo $row['p_id'];?>" name="commentmarkcode" class="commentMarkcode" size="35" maxlength="20"> <br clear="all" /> <span id='commentMarkCodeCompCodec-<?php echo $row['p_id'];?>'><b><script type="text/javascript">viewcodec();</script></b></span> <input type="hidden" id="commentMarkCodeComp-<?php echo $row['p_id'];?>" name="commentMarkCodeComp" value=""> <br clear="all" /> <br clear="all" /> <a id="SubmitComment" style="float:right" class="small button comment"> Comment</a> </div> </form> <?php } ?> Hi guys, Let me explain simply what I do and what I'm trying to achieve: I got a couple of comboboxes were the user selects a series of numbers. Once a selection is made, the value is appended to an input box. The idea is that the appended values form a telephone number, or at least part of one, that will then be used to search trough a database to look for a matching number. The code below is what I have done so far: Code: <script type="text/javascript"> function displayIndicatif(){ var sel = document.getElementById("indicatif"); var text = sel.options[sel.selectedIndex].value; var out = document.getElementById("blabla"); out.value += text+"\n"; } function displayBloc(){ var sel1 = document.getElementById("bloc"); var text1 = sel1.options[sel1.selectedIndex].value; var out1 = document.getElementById("blabla"); out1.value += text1+"\n"; } </script> [...] <input type="text" id="blabla"/> [..] <select id="indicatif" onChange="displayIndicatif();"> <option value="021">021</option> <option value="022">022</option> <option value="031">031</option> </select> <select id="bloc" onChange="displayBloc();"> <option value="555" class="021">555</option> <option value="666" class="021">666</option> <option value="777" class="021">777</option> </select> Basically what happens now is this: combobox indicatif: 021 | 022 | 031 combobox bloc: 555 | 666 | 777 If I select "021" from indicatif, the script will append 021 to the input "blabla". The problem is, if I now select "022", the input will show "021022" instead of replacing the 021 with 022. What I would like is that, for each combobox, the script replaces the selected value with the new one instead of simply appending it, like instead of say 021022555666 it would show 021555 or 022666 or 021666 depending on what is selected...you get the idea? Is this doable? Needless to say I'm a total noob at javascript...I adapted the code I got now from some other guy who was trying to achieve almost the same thing and adapted it to my needs, or least, tried to, but now I'm stuck. Any help is appreciated! Thanks Hate to ask this as I know it's an easy one but surprisingly Google turns up no clear/simple answers! I'm modifying some old code and am not JS programmer (I'm a PHP programmer) and this is driving me nuts. The existing code makes sure that when the form is submitted that there isn't a missing value. There's also some hidden input values. The JS starts out function checkform(orderform) and the form tag includes onsubmit="return checkform(this);"> I can add an alert to the form to see varius input values, such as a hidden value for the input name 'description' I can use: alert (orderform.description.value) Eazy peazy. However the form has two different input type=image buttons now and I need to do some branching in the JS depending on which image button they press. I recall IE had an issue where it only sends the x and y coordinates So I figure an easy to determine which image button was pressed is just check to see if the x or y value for each button is non-zero. But I can't for the life of me figure out how to access the value. Example: alert (orderform.button1.x.value) doesn't work. Can someone refresh my memory or suggest an entirely different method for detecting which image button was used to submit a form? THanks in advance! print "<Font face=\"calibri, Arial\"><table id=\"rnatable\" border=2px width=100%>"; print "<th></th>"; print "<th>a</th>"; print "<th>b</th>"; print "<th>c</th>"; print "<th>d</th>"; print "<th>e</th>"; print "<th>f</th>"; print "<th>g</th>"; while($array = mysql_fetch_array($sql_query)) { $id=$array['a']; print "<tr id=\"newtr\">"; print "<td><input id=\"check\" type=\"checkbox\" name=\"keyword[]\" value=\"$id\" ></td>"; print "<td>".$array['a']."</td>"; print "<td>".$array['b']."</td>"; print "<td>".$array['c']."</td>"; print "<td>".$array['d']."</td>"; print "<td>".$array['e']."</td>"; print "<td>".$array['f']."</td>"; print "<td> <a href=\"http://localhost/rnasearch/retrieve.php?a=$id\">bla</a> </td></tr></font>"; } print "</table>"; } this is part of a php searchengine script that i wrote to retrieve data from a database and as you can see the last column that is g contains a link which when clicked takes the user to the second php script which retrieves additional information of that entry, but this is done for only single entries so as you can see i introduced checkboxes so that the user can check any number of checkboxes and retrieve information as per their wish now to do this i created a <input type=text where i want the value of these checkboxes i.e. $id to be posted in a delimited format so that the user can then click the corresponding button and retrieve the information this is the code <div id="floatMenu"> <ul class="menu1"> <center><li><form name="senddata" method="POST" action="http://localhost/retrieve.php" style="display:inline;"><input id="fasta" type="text" class="multitext"><input name="Fasta" type="Submit" value="Retrieve Fasta"></form> this is a css floating menu....so far so good....everything went fine.... after this i had to write a javascript to do this and i've been stuck there searching forums for the last 4 days! this is the javascript i found from somewhere which came close to doing wht i wanted it to do window.onload = function () { var cb = document.getElementById('check'); var fasta = document.getElementById('fasta'); cb.onclick = function () {fasta.value = cb.value + ","; };}; this script only sends the value of the first checkbox in the table, the others are not found by it, mind you its not the first checkbox selected its the first checkbox that is present in the table how can i resolve this problem so that even if i have n number of checkboxes in my table, if the user chooses to do so they can retrieve n number of information....please help i've almost lost hope in this! im suppose to validate an ID text field so that is it mandatory, and must be 6 numeric digits. The code i have for the ID field is: Code: <form id="ThisForm"> <label for="emId"> Employee ID: </label></td> <input type="text" name="empID" id="emId" ;"/> </form> I'm beginner to javascript and really has no idea what to do, can someone help pls. Anyone know how do I use javascript to limit the numeric amount enetered in a text box less than 1000?
I'm trying to figure out how to add a length paramater to this function. Not quite sure how to do it. here's what I tried: Code: var phone = document.getElementById('phone'); if(isNumericdashes(phone, "Please enter a valid phone number")){ return true; } function isNumericdashes(elem, helperMsg){ var numericExpression = /^[0-9\(\)-]+$/; if(elem.value.match(numericExpression) &&(elem.length > 9)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } i have been trying to edit the below code so i can validate text fields and numeric fields but whenever i try it bypasses all validation and executed the php script. Can someone please let me know what i'm doing wrong fld = form.elements['name']; if ( !isValidText( fld.value ) ) { msg = 'The name is not valid.'; addValidationField(fld); addValidationMessage(msg); } function isValidText(val) { var re = /^\s{1,}$/g; if ((mytext.value.length==0) || (mytext.value==null) || ((mytext.value.search(re)) > -1)) { return true; }else { return false; } } Code: fld = form.elements['email']; if ( !isValidEmail( fld.value ) ) { msg = 'The email address is not valid.'; addValidationField(fld); addValidationMessage(msg); } the above code calls: Code: function isValidEmail(val) { var re = /^[\w\+\'\.-]+@[\w\'\.-]+\.[a-zA-Z]{2,}$/; // /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,4}(\.[a-z]{2}){0,2})$/i; if (!re.test(val)) { return false; } return true; } the entire script is as follows Code: /* order form code from dyn-web.com */ // onchange of qty field entry function getProductTotal(field) { clearErrorInfo(); var form = field.form; if (field.value == "") field.value = 0; if ( !isPosInt(field.value) ) { var msg = 'Please enter a positive integer for quantity.'; addValidationMessage(msg); addValidationField(field) displayErrorInfo( form ); return; } else { var product = field.name.slice(0, field.name.lastIndexOf("_") ); var price = form.elements[product + "_price"].value; var amt = field.value * price; form.elements[product + "_tot"].value = formatDecimal(amt); doTotals(form); } } function doTotals(form) { var total = 0; for (var i=0; PRODUCT_ABBRS[i]; i++) { var cur_field = form.elements[ PRODUCT_ABBRS[i] + "_qty" ]; if ( !isPosInt(cur_field.value) ) { var msg = 'Please enter a positive integer for quantity.'; addValidationMessage(msg); addValidationField(cur_field) displayErrorInfo( form ); return; } total += parseFloat(cur_field.value) * parseFloat( form.elements[ PRODUCT_ABBRS[i] + "_price" ].value ); } form.elements['total'].value = formatDecimal(total); } function finalCheck(form) { clearErrorInfo(); var msg = '', fld; // final check of quantity entries' validity for (var i=0; PRODUCT_ABBRS[i]; i++) { var cur_field = form.elements[ PRODUCT_ABBRS[i] + "_qty" ]; if ( !isPosInt(cur_field.value) ) { msg = 'Please enter a positive integer for quantity.'; addValidationField(cur_field) } } if (msg) { // one msg for qty flds addValidationMessage(msg); } ///////////////////////////////////////////////////////////////////// // add check on email and any other required fields here fld = form.elements['email']; if ( !isValidEmail( fld.value ) ) { msg = 'The email address is not valid.'; addValidationField(fld); addValidationMessage(msg); } // ///////////////////////////////////////////////////////////////////// if (msg) { // if any error msg's, display and cancel submission displayErrorInfo( form ); return false; } // check if a quantity entered if (form.elements['total'].value == 0) { msg = "You haven't ordered anything."; addValidationMessage(msg); displayErrorInfo( form ); return false; } return true; } function isValidEmail(val) { var re = /^[\w\+\'\.-]+@[\w\'\.-]+\.[a-zA-Z]{2,}$/; // /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,4}(\.[a-z]{2}){0,2})$/i; if (!re.test(val)) { return false; } return true; } // onclick function checkValue(field) { if (field.value == 0) field.value = ""; } // onblur function reCheckValue(field) { if (field.value == "") field.value = 0; } function isPosInt(val) { var re = /^\d+$/ if ( !re.test(val) ) { return false; } return true; } // format val to n number of decimal places // modified version of Danny Goodman's (JS Bible) function formatDecimal(val, n) { n = n || 2; var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) ); while (str.length <= n) str = "0" + str; var pt = str.length - n; return str.slice(0,pt) + "." + str.slice(pt); } I'm having trouble figuring out this code. I have a isInitialsTextValid function that checks to see if the user enters their initials in the correct format. Then I have a function checkInitials. In the checkInitials function I am supposed (1)to declare a variable to be used for the boolean value returned by the isInitialsTextValid function.(2)call the isInitialsTextValid function.(3)If the value returned is false, place focus back on initials textbox.(4)If the value return is true call the submit function. I'm not sure what I am doing wrong, but I get a checkInitials is no defined error from firefox and it is pointing to my xhtml file. Here is the relevant code. XHTML FILE Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Form Example</title> <script type = "text/javascript" src= "Lab17.js"> </script> </head> <body onload="giveInitFocus();"> <form name = "form1" action = ""> <p> <input type = "button" value = "Total Cost" onClick = "checkInitials();" /> <input type = "reset" value = "Reset Order Form" name = "reset" /> </p> <hr /> <p> Please Enter the Cashier's Initials. </p> <p> <label> Cashier's Initials: <input type = "text" name = "initials" id = "initials" /></label> </p> <p> JAVASCRIPT FILE Code: function isInitialsTextValid() { var init = document.form1.initials; var position = init.value.search(/^[A-Z]{2,3}$/); if(position !=0) { alert("Initials must be 2 or 3 capital letters" + "\n Please re-enter"); return false; } else return true; } function checkInitials() { var returned; isInitialsTextValid(); if(returned == false) { document.form1.initials.focus(); } else if(returned == true) { handleSubmitClick(); } } |