JavaScript - Input Validation
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. Similar TutorialsAnyone know how do I use javascript to limit the numeric amount enetered in a text box less than 1000?
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 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'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(); } } As you can see the above warning will be only shown when there is an error while inserting the data into the login form. Now I have tried to achieve it by: Hiding the div say "warning". Use a javascript while submitting the form to check for input validation. If found any error, the hidden div "warning" will show above the form as shown as in the image. I have tried it in Edit fiddle - JSFiddle Ples help 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 Hi I have a problem with a form in my site he http://www.21centuryanswers.com/submit.php if no field is filled and you click submit, an alert will be shown, yet the next page will still load! How do I fix it? the code for the form is: <form action="privacy.php" method="post" onsubmit="return checkform(this);"> <fieldset> <center> E-mail: <input type="textfield" name="email" size="60" value="" /><br/></br> Question: <input type="textfield" name="question" size="70" value="" /><br/><br/> <input type="submit" value = "Submit"/> </center> </fieldset> </form> and here is the validation script: <script language="JavaScript" type="text/javascript"> <!-- function checkform ( form ) { // ** START ** if (form.email.value == "") { alert( "Please enter your email." ); form.author.focus(); return false ; } if (form.question.value == "") { alert( "Please enter the question." ); form.title.focus(); return false ; } // ** END ** return true ; } //--> </script> Please help! I have a problem with adding new inputs to a form (if and when required), Internet Explorer is fine but in Firefox if any previous input fields are filled when the more button is clicked they get reset to blank. JS: Code: fields = 0; function addInput() { if (fields != 100) { document.getElementById('input').innerHTML += "<input type='text' name='input[]' size='30' />"; fields += 1; } else { document.getElementById('input').innerHTML += "<br />Maximum 100 fields allowed."; document.form.add.disabled=true;} } form: Code: <form action="index.php" method="post"> <div id="input"> <input type="text" name="input[]" size="30" maxlength="15" /> </div> <!-- button --> <div id="more"> <input type="button" onclick="addInput()" name="add" value="More" /> </div> <!-- // button --> <input type="submit" name="submit" value="Submit" /> </form> as usual any help is appretiated .. I am thinking this should be fairly easy but yet I am not getting far. I want to have a form with a single text imput field for a zip code. Depending on which zip code the user enters will determine which url they will be sent to. If they enter a zip code which is not in the script, they would be sent to a default url. I am also assuming this can be accomplished with javascript. Any help is greatly appreciated. Hey all. I have a simple validation I need to do. I need to just make sure that a Checkbox is checked, and that a Text field has content. Sounds simple but I cannot find any thing that has a check and a text field. Here what I have. Can I modify this script to do this? A Checkbox MUST be checked and Text field MUST be filled out. This currently does the text field fine, but no Checkbox obviously. How can I add a checkbox validation to this? Thats it. Any help is appreciated. Code: <script type="text/javascript"> var textFields = ["digsig"]; function validateForm( ) { var oops = ""; // must initialize this! var form = document.sig; for ( var t = 0; t < textFields.length; ++t ) { var field = form[textFields[t]]; var value = field.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim the input if ( value.length < 1 ) { oops += "You MUST enter your Digital Signature"; } } if ( oops != "" ) { alert("ERROR:" + oops); return false; } } } </script> Hello all, new here Seems like a very nice place to be apart of. I have my website www.gebcn.com. If you view source you will see all that I have done, but more importantly my problem. I have the JS code at the top there and I am unable to W3C validate my HTML because of the JS. I am using XHTML strict and would like to stay using it. The JS I have at the top is my form validation code. I am able to do any validating that I need with this "snippet" of code, I have shrank it from my library version just to use for this newsletter. Until now W3C validating was not important now for some reason it is and I am faced with this problem. I am not a Javascript guy more of a HTML/CSS guy and I can manipulate JS to suit my needs. <problem> I have tried to make this "snippet" of JS code an external file but receive multiple errors with the JS calling for the FORM NAME as it is not on the same page. The form NAME=NEWSLETTER is another problem, as W3C says I am unable to use attribute "NAME" in this location. <problem> I would like to keep the JS close to how it is now as I have a library to use this JS over and over again. Any pointers in the right direction or solutions to my problem would be greatly appreciated. Thanks! Hopefully it is not to hard huh If there is anything anyone needs, the code pasted here, or anything else please let me know. Thanks again! Hi, i want to set an input value to the same value as the input selected from another input on the same form so when the user selects input 1 i want the hidden input2 to get the same value im guessing i use onsubmit because its hidden so there wont be a focus or blur this would be part of the input Code: onsubmit="(this.value = this.othervalue)" othervalue being the other input name="othervalue" is that the correct syntax Hi, i have an input value array for customer ids, i also need to make a copy of that array into another input element on submit to use for another process. So far here is what i have come up with regarding the js the current html is this Code: <!-- original input --> <input id="cb<?php echo $i;?>" name="cid[]" value="<?php echo $commissions[$i]['id'];?>" onclick="isChecked(this.checked);" type="checkbox" /> <!-- this is new html input which is outside the $i loop that i need a copy of cid[] stored on submit <input type="hidden" name="ids[]" onsubmit="valueTovalue();" /> <!-- here is the js so far --> <script type="text/javascript"> function valueTovalue() { var valin = document.adminForm.cid.value; //cid is the array cid[] document.adminForm.ids.value = valin; //copy the array to the new input element array ids } </script> so basically if they click 1 cid then ids will also show 1, if they click all cid then ids will show all as well. will that work the way i have it, am i even close here.. thanks update: what i have seems to work fine for text values or string values but not for arrays, what am i missing that it wont copy an array? Array ( [cid] => Array ( [0] => 1 ) [task] => remarksonly [remark] => hhhyyy [boxchecked] => 1 [ids] => Array ( [0] => ) ) am i getting closer lol Code: function valueTovalue() { var valin = cid.concat; document.adminForm.ids.value = valin.concat; return(true); this has to be close i hope Code: document.adminForm.ids.value = [].concat(document.adminForm.cid); Hi all can someone guide me (total JS newbie) on this presumably pretty easy task? I have a "parent" page with some text inputs in it (a form). This is what I am after: -when the user clicks a link it pops open a new window via JS - "child" (this is working). -in the "child" window there are also some text inputs (another form) (done). -when the user changes the value for 'testChild_textInput_4' in the child window, then I want it to automatically set this same value, to effectively overwrite, what is currently in 'testParent_textInput_2' in the parent window. Presumably this involves an onChange event, but it is also OK with me if the needful (the text input's value in the parent window being overwritten) happens upon the child window's form submit. If anyone can show me either trick, I would be thrilled! I set up a test page to make this all easy to talk about: http://www.yellow-turtle.com/testDumpMe_parent.html Please let me know! Thanks! -John 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! I keep getting validation errors for using && as and. I've read to put "&" in place of it, but whenever I do this, the code stops working. I've tried seperate parenths, and still confused. anyone help to make this work and validate at the same time? if (first=="" && last=="") first = last = "Unknown"; if (first == '') document.writeln(last); else if (last == '') document.writeln(first); else document.writeln (last + ", " + first); Hello, I dont know if I am going about this the right way, but.. I am trying to validate an email address. If the email is a valid looking email address, it will render the submit button disabled to prevent dupe's while the rest of the script processes. The email validation portion works, but, the part where it renders the form submit button disabled does not: <script type="text/javascript"> function validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@"); dotpos=value.lastIndexOf("."); if (apos<1||dotpos-apos<2) {alert(alerttxt);return false;} else {return true; submit.disabled = true;} } } function validate_form(thisform) { with (thisform) { if (validate_email(email,"Please enter a valid email address.")==false) {email.focus();return false;} } } </script> Any guidance or help would be apreciated. Hello to everyone i need to validate a form Based on radio buttons and text box my code so far Code: <html> <head> <title>My Page</title> <script type="text/javascript"> function validate(thisform) { document.getElementByName("bank");//text box // validate myradiobuttons radio = -1; for (i=thisform.day.length-1; i > -1; i--) { if (thisform.day[i].checked) { radio = i; i = -1; } } if (radio == -1) { alert("You must select all values for the clock !"); return false; } else { return true; } } //bank code validation if (document.getElementByName("bank").value.length>=6) { return true; } else { alert("you must input maximum 6 digit (123456) !"); return false; } } </script> </head> <body> <form action="form-output.php" method="post" id="form"> <input type="radio" name="day" value="f" onclick="dayofweek(this)" /> Sunday (default) <input type="radio" name="day" value="s" onclick="dayofweek(this)" /> Sun </p> <input type="radio" name="month" value="a" onclick="dateformat(this)" /> 28th March 2010 (default) <input type="radio" name="month" value="b" onclick="dateformat(this)" /> 28 March 2010 <input type="radio" name="month" value="c" onclick="dateformat(this)" /> 28th Mar 2010 <input type="radio" name="month" value="d" onclick="dateformat(this)" /> 28 Mar 2010 <input type="radio" name="month" value="e" onclick="dateformat(this)" /> 28/03/2010 <input type="radio" name="month" value="f" onclick="dateformat(this)" /> 28th March 10 <input type="radio" name="month" value="g" onclick="dateformat(this)" /> 28 March 10 <input type="radio" name="month" value="h" onclick="dateformat(this)" /> 28th Mar 10 <br/> <input type="radio" name="month" value="i" onclick="dateformat(this)" /> 28 Mar 10 <input type="radio" name="month" value="j" onclick="dateformat(this)" /> 28/03/10 <input type="radio" name="month" value="k" onclick="dateformat(this)" /> 28th March <input type="radio" name="month" value="l" onclick="dateformat(this)" /> 28 March <input type="radio" name="month" value="m" onclick="dateformat(this)" /> 28th Mar <input type="radio" name="month" value="o" onclick="dateformat(this)" /> 28 Mar <input type="radio" name="month" value="p" onclick="dateformat(this)" /> 28/03 </p> <input type="radio" name="time" value="a" onclick="timeformat(this)" /> 5:28:12 am (Default) <input type="radio" name="time" value="b" onclick="timeformat(this)" /> 5:28 am <input type="radio" name="time" value="c" onclick="timeformat(this)" /> 5:28:12 <input type="radio" name="time" value="d" onclick="timeformat(this)" /> 5:28 <input type="radio" name="time" value="e" onclick="timeformat(this)" /> 17:28:12 <input type="radio" name="time" value="f" onclick="timeformat(this)" /> 17:28 </p> Input a short Bank Code <input type="text" name="bank" size="10" onblur="JavaScript:alert('You must insert a Bank Code')" /></br> <input type="submit" name="submit" onclick="validate(form);return false;" value="Submit" /> <input type="reset" name="reset" value="reset" /> </form> </body> </html> i need on submit to validate if user select values from 3 radio groups and insert the proper data to text box. if not i want to return the proper alerts in text box also i want when lose focus to validate so i put this Code: onblur="JavaScript:alert('You must insert a Bank Code')" it's ok? Thanks in Advance Hey. Could someone point me in the direction of why this is not working, it worked in my last program, but not since I have changed things. I have a standard html form Code: <form method="POST" onsubmit="return validate_form(this)" action="anniversaryPreview.php"> <p class="demo5">Senders Name<a class="textFields2"> <input type="text" name="sender" value="e.g. Love from Nick" size="30" maxlength="35" /></a></p> <p class="btn2" > <input type="submit" value="Preview"></p> </form> And this should call up return validate_form(this) before bringing up the php page. Now the validator is just Code: function validate_required(field, alerttxt) { if (field.value == null || field.value == "") { alert(alerttxt); return false; } else { return true; } } function validate_form(thisform) { if (validate_required(thisform.name,"Please specify the receivers name.")==false) { thisform.name.focus(); return false; } if (validate_required(thisform.sender,"Please specify the sender's name.")==false) { thisform.sender.focus(); return false; } } (This is not in the html file, but its own seperate file) I cant see if I have made any mistakes with the variables names or something, or what I am doing wrong. Dont get any errors, just nothing happens if I leave my forms fields blank. Anyone have an idea of whats going on here? cheers In my project i have a from which have several fields. The form is <form name="reg" action="payment.jsp" method="post"> ----------- <tr> <td>First name:</td> <td><input type="text" name="firstname"/></td></tr> -------------------------- <input type="submit" value="Next" onclick="fun()" /> ------------ </form> Then to validate the fields i have used JavaScript.They are validating rightly using a alert box. But when i am pressing ok of the alert box the control is passing to the page i have written in action of the form.I want when i will press ok it should come back to the same page.Only if all fields are then it should go to the page refereed in action. Can anyone help me? The JavaScript code is <script type="text/javascript"> function fun() { var x=document.forms["reg"]["firstname"].value; if (x==null || x=="") { alert("First name must be filled out"); } |