JavaScript - Text Field Validation For Phone Number
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; } Similar TutorialsHi 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. Need 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> 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> Arrrgggghhhhhhhhh - help.... - LOL Now I've got that over with, hope someone can help. Am just learning regular expressions and am trying to validate UK format telephone numbers (have had an extensive look on the web and only examples I can find are US tests). Anyway, I want to learn to do it myself. UK phone number rules a Must start with a 0 in position 1 Next 2 to 4 characters must be a number Next character can be a space or a dash Next 6 to 9 characters can be a number, space or dash only Anyway, as I say, am new to regular expressions and trying to learn so I tried to write the expression to fit the rules above - see below: Code: ^[0]{1}\d{2,4}\s|-{1}\d|\s|-{6,9}$ My logic (for what it's worth - LOL) tells me this should work, but it doesn't - it accepts letters as well - which I really don't understand yet. Anyway - hope someone can help. Thanks Dominic Good Afternoon All, I am slowly learning how to validate forms and the next topic I'm learning is the phone feature! My code isn't working and not sure why! I read other opinions and tried to follow some templates but again.. Nothing is working out for me.. Here is the code function validatePhone(fld) { var stripped = document.validatePhone.phoneNumber(/[\(\)\.\-\ ]/g, ''); if (document.validatePhone.phoneNmbr == "") { alert("Do not leave this field blank"); } else if (isNaN(parseInt(stripped))) { alert("Only enter numerical digits only"); } else if (!(stripped.length == 10)) { alert("No More or Less than 10 Digits"); } return error; } <body> <form name="validatePhone" action="" method="get"><br /> <br /> <input type="text" name="phoneNumber" value="" onClick="return validatePhone(fld)"> <br /> <br /> <input type="button" name="button" value="Validate Phone Number" > </form> </body> </html> If you have any suggestions or can provide links of how I can 1-Provide an alert if the field is blank 2-Provide an alert if non numerical digits are entered 3-Provide an alert if more than 10 digits are entered I think I am on the right track but need more of a push.. I'm not seeking a solution, just information to get me on that right track as I am extremely confused. Also.. I feel like I should be using a isDigit function? I am trying to validate textboxes on my form. I got everything but phone number. I have three different textboxes. One for area, one for first three, and last one for last 4numbers. everything just need to be digit numbers I guess. What is REGEX expression should be for those three different area?
Just wondering what the code is for a phone number to be displayed nn-nnnnnnnn for example: 67 43289482 current code is Code: var pn = document.contact_form.phonenum.value; if ((pn.length != 10) || (/[^0-9]/g.test(pn))) { // 10-digit phone number alert ( "Please fill in your 10-digit telephone number" ); return false; } I would like to use Javascript to format a UK telephone number to this layout: 00000 000000, preferably as the user enters it in the form. I am using Actinic's ecommerce system, and have already used the code in this link to format the postcode. http://community.actinic.com/showthread.php?t=45487 I have found the code here http://javascript.internet.com/forms...ne-number.html but it is for American telephone formats, and seems far too complicated! Has anyone come across any code that will do this for UK phone numbers? It would need to remove all white space, and then insert a space after 5 numbers. I am not bothered about validation checks etc. Thanks for your help i see alot of forms where the phone number field is split into 3 boxes and you can type smoothly from the first box to the last....here is the beginning code i have now for my form Code: <form id="contactform" action="contact-submit.php" method="post"> <!-- form fields --> <div class="form"> <label for="name">Name<em>•</em></label> <input class="textbox required" type="text" name="name" id="name" /><br /> <label for="email">E-Mail<em>•</em></label> <input class="textbox required email" type="text" name="email" id="email" /><br /> how do i add a phone number field in there that has 3 connected fields? This is what I have so far, it is a template I copied from my working E-mail validation. I'm assuming I have to make it so it's just an array of numbers but I really don't know Java too well. Essentially I just want numbers only to be accepted into the phone field. Code: else if(fieldType == 'phone') { if((required == 1 && fieldObj.value=='') || (fieldObj.value!='' && !validate_phone(fieldObj.value))) { fieldObj.setAttribute("class","mainFormError"); fieldObj.setAttribute("className","mainFormError"); fieldObj.focus(); return false; } } function validate_phone(phoneStr) { apos=phoneStr.indexOf("@"); if (apos<1||dotpos-apos<2) { return false; } else { return true; } } I am Gururaj. I have written a form in HTML which contains username,lastname,email,password and submit. I have written a javascript to validate this form [validate(username,lastname,email,password)]. On submit this javascript function will be called and hence form get validated. I am passing all the arguements(username,lastname,email and password) to the javascript function.. Is it possible to make me a code such that it should call an individual function for each field in the form.for ex:if i have not entered username, last name in the form and attempt to submit, only username arguement should be passed to the function as it comes first in the form. In other sense i want to validate individual text field validation of my form. So can anybody help me.It will be very needful to me. Hi, I have a form on my website and I want to validate the phone field. I found a good script to do it but I need to combine the script with the other validation that I have on my form. Can you help me add this phone validation script into the other validations that I have so that it is just one javascript? Here is the phone validation script: <script language = "Javascript"> /** * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/) */ // Declaring required variables var digits = "0123456789"; // non-digit characters which are allowed in phone numbers var phoneNumberDelimiters = "()- "; // characters which are allowed in international phone numbers // (a leading + is OK) var validWorldPhoneChars = phoneNumberDelimiters + "+"; // Minimum no of digits in an international phone no. var minDigitsInIPhoneNumber = 10; function isInteger(s) { var i; for (i = 0; i < s.length; i++) { // Check that current character is number. var c = s.charAt(i); if (((c < "0") || (c > "9"))) return false; } // All characters are numbers. return true; } function trim(s) { var i; var returnString = ""; // Search through string's characters one by one. // If character is not a whitespace, append to returnString. for (i = 0; i < s.length; i++) { // Check that current character isn't whitespace. var c = s.charAt(i); if (c != " ") returnString += c; } return returnString; } 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 checkInternationalPhone(strPhone){ var bracket=3 strPhone=trim(strPhone) if(strPhone.indexOf("+")>1) return false if(strPhone.indexOf("-")!=-1)bracket=bracket+1 if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false var brchr=strPhone.indexOf("(") if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false s=stripCharsInBag(strPhone,validWorldPhoneChars); return (isInteger(s) && s.length >= minDigitsInIPhoneNumber); } function ValidateForm(){ var Phone=document.frmSample.txtPhone if ((Phone.value==null)||(Phone.value=="")){ alert("Please Enter your Phone Number") Phone.focus() return false } if (checkInternationalPhone(Phone.value)==false){ alert("Please Enter a Valid Phone Number") Phone.value="" Phone.focus() return false } return true } </script> Here are the validations for the other fields: <script type="text/JavaScript"> function validate_form(){ err = 'The following fields are not correct filled:\n'; if (document.form1.name.value == ''){ err += 'No First Name.\n'; } if (document.form1.from.value == ''){ err += 'No Email Address.\n'; } if (document.form1.elements['custom State'].value == ''){ err += 'No State.\n'; } if (document.form1.elements['custom Phone'].value == ''){ err += 'No Phone.\n'; } if (emailCheck(document.form1.from.value) == false){ err += 'No Valid email.\n'; } if (document.form1.terms.checked != true){ err += 'You did not agree with the terms.\n'; } if (err != 'The following fields are not correct filled:\n'){ alert (err); return false; } else{ return true; } } var str_vars = ''; function all_fields(){ str_vars = ''; el = document.form1; for (var i = 0; i < el.elements.length; i++) { if (el.elements[i].value != '') str_vars += el.elements[i].name+'='+el.elements[i].value+'&'; } str_vars = str_vars.substr(0,str_vars.length-15);; } </script> Thank you, Leroy Hi all, Thanks for reading. I'm having an issue trying to accomplish the following - I have a text field (field1) already displayed on the HTML page. However, there's a link where you can add additional text fields to the page as well. When the link is clicked, the second text field is added successfully (field2), and when the link is clicked again, the third text field (field3) is added successfully. However, the third field does not add itself to the page, and the text for anything greater than a third field also isn't displayed after. This obviously means that my "fields" variable is not working right, so I'm wondering, would anyone be able to assist me to help me get that variable processing correctly? Code: <script language="javascript"> fields = 1; function addMore() { if (fields = 1) { document.getElementById('addedMore').innerHTML = "<input type='text' name='field2' size='25' /> <span>Field 2.</span>"; fields = 2; } else if (fields = 2) { document.getElementById('addedMore').innerHTML = "<input type='text' name='field3' size='25' /> <span>Field 3.</span>"; fields = 3; } else { document.getElementById('addedMore').innerHTML = "Only 3 fields are allowed."; document.form.add.disabled=true; } } </script> Here is the code in my HTML - Code: <input type="text" name="field1" size="25" /> <span>Field 1.</span> <div id="addedMore"></div> <p class="addMore"><form name="add"><a onclick="addMore()">Add another field.</a></form></p> Thank you very much. Hi there, I would like to allow the "+" sign in my 3 textboxes. When the user does not put the "+" sign in the textboxes, and it is being validated, the system will allow it to pass. Also, it must check that it has at least 8 digits. 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> <link rel="stylesheet" type="text/css" href="CSS files/specialAlignment.css" /> <link rel="stylesheet" type="text/css" href="CSS files/externalCSS.css"/> <script language = "javascript" type = "text/javascript"> function check() { var fields = new Array("Office Telephone", "Mobile Telephone","Fax Number"); var telnr = /(^[\+]?[\d]{8,20}$)/; var index = new Array(); for(var i = 0; i < fields.length; i++) { var arrayFields = document.getElementsByName(fields[i]); for(var j = 0; j < arrayFields.length; j++) if(!(arrayFields[j].value) == "") { arrayFields[j].className = "defaultColor"; } else { arrayFields[j].className ="changeToRed"; index.push(fields[i]); } } if(index != 0) { joinComma = index.join(', '); alert('The field(s) corresponding to '+ joinComma + ' is/are not filled in.'); } } function noSpace(e, dec) { var key; var keychar; if (window.event) { key = window.event.keyCode; } else if (e) { key = e.which; } else { return true; } keychar = String.fromCharCode(key); if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) /*|| (key==107)*/) { return true; } else if ((("0123456789").indexOf(keychar) > -1)&& check(telnr.test(tfld))) { return true; } else if (dec && (keychar == ".")) { return true; } else return false; } </script> </head> <body> <label> *Office Telephone:</label> <input id="Text16" type="text" name="Office Telephone" onkeydown="return noSpace(event)" /> <br /> <br /> <label> *Mobile Telephone:</label> <input id="Text17" type="text" name="Mobile Telephone" onkeydown="return noSpace(event)" /><br /> <br /> <label> *Fax Number:</label> <input id="Text18" type="text" name="Fax Number" onkeydown="return noSpace(event)" /> <br /> <br /> <input id="Submit17" type="submit" value="Submit" onclick="return check()"/> </body> </html> 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); } I have a text field, call it income, that when the input is > 0 I need to dynamically show the next text box, and if it is blank hide the next text box. I would like to use onBlur but can't seem to get it to work. Can I do this? Help 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. hi all, i was hoping somebody could help me out. i'm trying to write a code that generates a random number between 1 and 9999 on page load, concatenates it with "pwn" at the start, and adds it to a disabled form text input box. this is the code i have below, but it's not working at all. any help would be greatly appreciated. in the head section Code: <script type="text/javascript"> function createcode() { var randomnumber = Math.floor(Math.random()*10000); var homecode = 'pwn' + randomnumber; } </script> my body tag Code: <body onload="createcode()"> and the form field itself Code: <input type="text" name="homename" id="homename" disabled="disabled" /> <script type="text/javascript"> document.getElementByID("homename").value = homecode; document.write(homecode); </script> thanks in advance. 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 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); |