JavaScript - Double Number Validation
Hi guys,
I have written a double validation as below function validateDouble(ele){ // Custom trim funcation, i have written if(trim(ele.value) != ''){ var a = /^\d+(\.\d{0,2})?$/.test(trim(ele.value)); if(a){ return true; }else{ return false; } }else { ele.value = '0.00'; return true; } } I have copied from the net But this validation doesnt work when we enter the value as .65 (Means, it should accept this also, Please help me to change the regular expression) and in the same time when we enter this with out prefix, it should auto change to 0.65. Can some one help me to add in the above function. Similar TutorialsNeed Phone Number Validation for my JavaScript, i can't work it out It currently has E-mail, Surname, Address and Name validation, This is my code at the moment: Code: <script language="JavaScript"> function echeck(str) { var at="@" var dot="." var lat=str.indexOf(at) var lstr=str.length var ldot=str.indexOf(dot) if (str.indexOf(at)==-1){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(at,(lat+1))!=-1){ alert("Please Enter a Valid E-mail") return false } if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(dot,(lat+2))==-1){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(" ")!=-1){ alert("Please Enter a Valid E-mail") return false } return true } function validate_required(field,alerttxt) { with (field) { if (value==null||value=="") { alert(alerttxt);return false; } else { return true; } } } function validate_form(thisform) { with (thisform) { if (validate_required(Name,"Name must be filled out!")==false) {Name.focus();return false;} if (validate_required(Surname,"Surname must be filled out!")==false) {Surname.focus();return false;} if (validate_required(Country,"Address must be filled out!")==false) {Country.focus();return false;} } { var emailID=document.submitting.email if ((emailID.value==null)||(emailID.value=="")){ alert("Please Enter a Valid E-mail") emailID.focus() return false } if (echeck(emailID.value)==false){ emailID.value="" emailID.focus() return false } return true } } function verifyEmail(form) { checkEmail = form.email.value if ((checkEmail.indexOf('@') < 0) || ((checkEmail.charAt(checkEmail.length-4) != '.') && (checkEmail.charAt(checkEmail.length-3) != '.'))) {alert("You have entered an invalid email address. Please try again."); form.email.select(); return false; } else { form.method="get"; form.rel="nofollow" target="_self"; form.action="myscript.cgi"; form.submit(); } } </script> Code: <form action="submit.htm" onsubmit="return validate_form(this)" method="post" name="submitting"> <span class="style5">Select Plant: <form id="form1" name="form1" method="post" action=""> <label> <select name="Item" id="Item"> <option>OMGwoopwoop Plant</option> <option>I'm Blue Plant </option> <option>Anonymous Plant</option> <option>Rawr Plant</option> <option>Chicka Plant </option> <option>Fruitopola Plant</option> <option>Whitoe Plant</option> <option>Wukidoo Plant </option> </select> </label> </p> <p>Name:<span class="style1"> <input type="text" name="Name" size="30"> <br> <br> </span>Surname: <span class="style1"> <input type="text" name="Surname" size="30"> <br> <br> </span>Address:<span class="style1"> <input type="text" name="Country" size="30"> <br> <br> </span>Email:<span class="style1"> <input type="text" name="email" size="30"> <br></span></p> Phone Number:<span class="style1"> <input type="text" name="phone" size="30"> <form action="submit.htm" onSubmit="return validate_form(this)" method="post"> <input type="submit" value="Submit"> </form> Hi there, I need to validate three textboxes and it will validate for numbers. How should I change my code to validate three textboxes? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <script type='text/javascript' language="javascript"> var validPhoneChar = "+"; // Minimum no of digits in an international phone no. var minDigitsInPhoneNumber = 10; function isInteger(s) { var i; for (i = 0; i < s.length; i++) { // Check that current character is a number. var c = s.charAt(i); if (((c < "0") || (c > "9"))) return false; } // All characters are numbers. return true; } function stripCharsInBag(s, bag) { var i; var returnString = ""; // Search through string's characters one by one. // If character is not in bag, append to returnString. for (i = 0; i < s.length; i++) { // Check that current character isn't whitespace. var c = s.charAt(i); if (bag.indexOf(c) == -1) returnString += c; } return returnString; } function checkRequirements(strPhone) { if(strPhone.indexOf("+") > 1) return false; s = stripCharsInBag(strPhone,validPhoneChar); return (isInteger(s) && s.length >= minDigitsInPhoneNumber); } function ValidateForm() { var Phone = document.getElementById("Text1"); //var Phone1 = document.getElementById("Text23"); if ((Phone.value == null)||(Phone.value == "")) //if match failed { alert("Please Enter your Phone Number."); Phone.focus(); return false; } /*if ((Phone1.value == null)||(Phone1.value == "")) //if match failed { alert("Please Enter your Phone Number0."); Phone.focus(); return false; }*/ if (checkRequirements(Phone.value) == false) { alert("Please Enter a Valid Phone Number."); Phone.value = ""; Phone.focus(); return false; } else alert("YAY!"); return true; } function NotAllowSpace() { // Get the ASCII value of the key that the user entered var key = window.event.keyCode; // Verify if the key entered was a Space if ( key == 32 ) { // If it was, then dispose the key and continue with entry window.event.returnValue = null; alert("Invalid,Please check") } else // If it was not, then allow the entry to continue return; } </script> </head> <body> <label>Office Telephone:</label> <input id="Text1" type="text" onkeydown = "return (event.keyCode != 32)"/><br /> <input id="Button1" type="button" value="button" onclick="return ValidateForm();" /><br /> </body> </html> I need to use Javascript to validate 3 textboxes, whereby the users can only key in numbers (because they are phone numbers related fields). If any of the textbox is empty, display an alert message to show which textbox is empty. I do not want to show many alert messages to show that, for example, text1 and text2 are empty, it will show two alert messages. I would need to show one "summarized" alert message instead. Next, check if the textbox matches the pattern (which is to check if it has the skeleton of a phone number). If it is, show an alert message that it is alright. Else, show that it does not match. Hi! I wish to know if one can dynamically validate a textbox that accepts telephone numbers. I plan to do this by: first selecting a country form a dropdown box. then validate the text box for the corresponding country selected... but do not have any idea how to do it! can you help me ? Hello, I have the following code that, among other things, should validate US telephone numbers with format: "(800) 800-8000" with hyphen, parenthesis and spaces optional. The regexp is: /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/ My main problem is that it validates also numbers like 800 or 800000000000000 etc. The code works perfectly on test pages but not on my website. Something similar happens also for the zipcode. Can someone please tell me what could be wrong? Thanks! Code: (function($){ $.fn.ax_validate = function(f){ stopAnim(); // just too much otherwise //console.log(typeof f + ', id = ' + f.id); var n, el, err = [], msg = [], fmats = { 'email': /^[\w\.\-]+\x40[\w\.\-]+\.\w{2,4}$/, 'phone': /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/, 'zip': /^\d{5}(-\d{4})?$|[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d/ }; $('input[type=text],textarea').each(function(i){ $(this).val( $.trim($(this).val()) ); }); $('label.req').each(function(i){ n = $(this).attr('for'); el = $('input[name=' + n + ']'); if (typeof fmats[n] != 'undefined' && !el.val().match(fmats[n])) { err.push(n); msg.push($(this).text() + ((el.val() == '') ? '' : ' (invalid format)')); $(this).animate({color: '#A60'}, 1000); } else if (el.val() == '') { err.push(n); msg.push($(this).text()); $(this).animate({color: '#A00'}, 1000); } else { $(this).css('color', '#0f4068'); } }); if (err.length == 0) { //alert('All ok!'); //f.submit(); return true; } alert('<b>Please fix the following required fields:</b><br /><br />' + msg.join('<br />')); //$('input[name=' + err[0] + ']').focus(); return false; }; })(jQuery); Hello All, I am not too good with javascript so I apologise in advance! I have a website form where people input their contact details and I need a script which allows the form to be submitted if the telephone number is correct and returns an error if the number is invalid, (preferably in a pop-up box - not on another page) which says something like "The telephone number you have entered is invalid. Please enter a valid UK landline or mobile number". For the number to be valid, it has to either start with an "01", an "02" or an "07" and be either 10, or 11 digits long. The user should also be able to enter space without an error (ie, the script should ignore spaces). Any suggestions would be much appreciated. Regards, AC I have a phone number field on my form that needs validation, but I'm not sure how to code this. I have the following function to validate a first name is entered and last name. The phone number field must match a 7 digit or 10 digit(with area code)phone number. I want to be able to include paranthese and/or hyphens for the valid phone number. function checkForm1() { if (document.forms[0].firstname.value.length == 0) { alert("You must put in a first name"); return false; } else if (document.forms[0].lastname.value.length == 0) { alert("You must put in a last name"); return false; } I have a function below where every time a question is submitted, it will add a new row in the table with a textbox which allows numbers entry only. My question is that I don't know how to code these features in this function: 1: I want the text box to be between 0 and 100, so if text box contains a number which is above 100, it will automatically change the number to the maximum number which is 100. Does any one know how to code this in my function below in javascript: Code: function insertQuestion(form) { var row = document.createElement("tr"); var cell, input; cell = document.createElement("td"); cell.className = "weight"; input = document.createElement("input"); input.name = "weight_" + qnum; input.onkeypress = "return isNumberKey(event)"; cell.appendChild(input); row.appendChild(cell); } When I used toFixed() method on a number, I thought that this method round a number to a specified approximation, but I got a surprising result, the number became string! 15.23689 .toFixed ( 2 ) ==> "15.24" So does it convert the number into string? I am trying to figure out how to make a random number I can plug into a script count down from that number at certain times of the day until it reaches 0. I would like it to reset itself at midnight every day. I'm trying to make it work with a script I found on here that resets itself at midnight every day. So instead of it counting down too fast, it would count down to the next number after a randomly generated number of minutes until it reaches 0. But it wouldn't necessarily have to end at 0 at midnight. It could go from 845 to 323 at the end of the day at a slower pace. Is that possible?
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> here is where the code is. http://simplythebest.net/scripts/DHT...script_15.html I need this to be able to open in the parent window not in another window. Or if someone could precribe a double drop box that works in "moonfruit" that would be great. Thank you very much for your time. David the following javascript code is for a page that has to different login sections (username and password) hospital admin i want them to login in their part using normal IDs(numbers) and password, and normal users to login in the other login boxes (using email address and password) , each login boxes have their own submit button. the problem is i can't check each of them alone. what i want to do is that if (for user) email and password entered and pressed his login button, to be headed to another page, while if hospital admin entered his id and password in his section and pressed login button, to be headed for a different page. help please ! Code: window.onload = initForms; function initForms() { for (var i=0; i< document.forms.length; i++) { document.forms[i].onsubmit = function() {return checkFields();} } } function checkFields(){ if(document.getElementById("userLogin").onclick) { if(isEmail(document.getElementById("userUsername").value)==false) { alert("Please enter a valid e_mail address."); document.getElementById("userUsername").focus(); return false; } if(document.getElementById("userUsername").value=="") { alert("Please enter your e_mail address."); document.getElementById("userUsername").focus(); return false; } if(document.getElementById("userPassword").value=="") { alert("Please enter your password."); document.getElementById("userPassword").focus(); return false; } } if(document.getElementById("hospLogin").onclick) { if(document.getElementById("hospUsername").value=="") { alert("Please enter your ID."); document.getElementById("hospUsername").focus(); return false; } if(document.getElementById("hospPassword").value=="") { alert("Please enter your password."); document.getElementById("hospPassword").focus(); return false; } } } function isEmail(mail) { var char1 = mail.split("@"); var y = mail.indexOf("@", 0); var e = mail.indexOf(".", 0); var w = mail.lastIndexOf(".", mail.length - 1); var sp = mail.indexOf(" ", 0); var pl = mail.indexOf("@.", 0); for (i = 0; i < mail.length; i++) { if (mail.charAt(i) == "/" || mail.charAt(i) == ":" || mail.charAt(i) == ";" || sp > 0 || pl > 0 || mail.charAt(i) == '"' || char1.length > 2 || y == -1 || y == 0 || e == 0 || w == mail.length - 1 || e == -1) { return false; } } } and there goes the HTML codes: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="script.css" /> <script type="text/javascript" src="script.js"></script> <title>Blood high res END</title> </head> <body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <div id="apDiv4" style="background:url(images/Blood-high-res-END_04.jpg) no-repeat"></div> <div id="apDiv1" style="background:url(images/Blood-high-res-END_01.jpg)"> <p>Hospital</p> <form name="hospForm" id="hospForm"> <input type="text" name="hospUsername" id="hospUsername" class="reqd" /><br /> <input name="hospPassword" type="password" id="hospPassword" class="reqd" /><br /><br /> <input name="submit" type="submit" id="hospLogin" value="Hospital log in" /></form></div> <div id="apDiv2" style="background:url(images/Blood-high-res-END_02.jpg)"></div> <div id="apDiv3" style="background:url(images/right.jpg)"> <a id="register" href="../User Registration Page/page.html" target="_self">Register Now</a> <a id="links" href="../Links/page.html" target="_self">Links</a> <p>Visitor</p> <form name="userForm" id="userForm"> <input type="text" name="userUsername" id="userUsername" class="reqd" /><br /> <input name="userPassword" type="password" id="userPassword" class="reqd" /><br /><br /> <input name="submit" type="submit" id="userLogin" value="User log in" /><br /></form> <a id="register2" href="../User Registration Page/page.html" target="_self">Register now</a><br /> <a id="forgot" href="../User Forgot Password/page.html" target="_self">Forgot Password</a></div> <div id="apDiv5" style="background:url(images/Blood-high-res-END_05.jpg) no-repeat"></div> <div id="apDiv6" style="background:url(images/Blood-high-res-END_06.jpg) no-repeat"> <p>Hello and welcome to Red Drop. By visiting our page,<br />you ensure to each and every one of the team crew <br />behind the stage, and to every lebanese person that<br />you are mentally prepared to donate a few drops of your<br />blood to the benefit of an anonymous stranger.<br /><br />With every drop you donate, you might be giving<br />a father, a mother or a child another day to live among<br />his family and his beloved persons.<br /><br />Register today and add donation blood to your frequently<br />social and humanitarian activities.</p> </div> <div id="apDiv7" style="background:url(images/Blood-high-res-END_07.jpg) no-repeat"></div> <div id="apDiv8" style="background:url(images/Blood-high-res-END_08.png) no-repeat"></div> <div id="apDiv9" style="background:url(images/Blood-high-res-END_09.jpg) no-repeat"></div> </body> </html> I havent added the server side scripts yet, i am planning to validate forms as much as possible using javascript first, and this is not for a real hospital, it's a graduation project, so to explain the point, on the page i have 2 seperated forms wich each having its own submit button, one to be used by hospital admins, and other to be used by users. For admins i just want to make sure their fields are not empty. For users i want to make sure their fields are not empty and their email field is valid. but when trying it, it's kinda only checks for the user fields. P.S: I apologize about not using codes, i didn't knew about this option. 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 have completed the necessary function and it does not need any changes however from the "alert" I need there has to be double quotes surrounding the search 'Lboro'. (I know I may be making a meal of the coding however the lecturer wants us to follow this due to everyone being at different levels of programming). I have used the '\' character however the double quotes do not end up in the position I require them?! My Coding function findAnyU (s){ var a = s , b , c , d , e = -1; for (var i = 0 ; i < pages.length && e == -1 ; i++){ b = pages[i].indexOf('['); c = pages[i].indexOf(']'); d = pages[i].substring(b+1, c).toLowerCase(); e = d.indexOf(s.toLowerCase()); } if(e >= 1) a += ' found' else a += ' not found' return (a) } alert (findAnyU('Lboro' , pages)); Current Alert = Lboro found Cheers George hello I have a listbox full of names on a PHP website and was wondering if there was a way to grab the value during a double click to bring me to another form to display the name and information? Hey I am almost done with my API boot system and with the way I am calling new files it seems to double boot how can I stop this from happening as the page fully loads and that but the loader shown in the IE tab doesn't stop and it says '1 item remaining' and that never goes, both stay until you click anywhere on the document, so I was wondering if there is a way to stop this. My code to call the js document in the file 'boot.js'. Code: var o = 'http://www.example.com/file.js'; document.write("<script src=\""+o+"\" type=\"text\/javascript\"><\/scr"+"ipt>"); And in index.html I have this script tag Code: <script type="text/javascript" src="http://www.example.com/boot.js"></script> I currently have a Drop-Down menu, which has headers you click on to show the links. This menu only allows one drop to be expanded at a time, and can be viewed here. I would like the headers to be able to have 'sub-headers' inside, which also drop-down,to reveal the links. I want them to have a different header colour, and to have the same rule where only one can be open at a time. while keeping the rule with the main headers. I have previously posted asking this, and got no reply, so I would really greatly appreciate any help and/support! Best Regards, Tim (P.S. I am still only learning JavaScript, and to make the current menu I have, took loads of help for a different project) Hi Can you please advise on this. When writing javascript what is best practice.... single or double quotes? I tried to research this and everyone contracdicts each other? thanks A hi I wonder if someone out there can help me. I am very new to javascript and i have manged to understand a little of a double combo box with description however I would now like to be able to not only change the comment underneth but also add an image. This image (along with the comment) changes everytime the dropdownbox changes. I just cant seem to add the image. Please can anyone help I would really appreciate it and be extremely grateful. gr T |