JavaScript - Help With Using Regular Expressions To Validate Letters Only
Hi wise javascript gurus, I am working on a small form that on the click of a button, it calls a function to validate a string that consists of 3 portions delimited with a dash("-") in the following format
XXX-NNNN-XXX where X are letters only where N are numbers only I have to use regular expressions to validate the first portion and verify that its exactly 3 characters long that are letters only if the first portion or "plant code" is larger then 3 characters long an alert gets display also if the first portion contains alphanumeric or numeric characters an alert gets displayed, the first portion has to be in letters only. down below is my code that is not functional at the time because I know for sure the way I check for regular expressions is a bet washy but thats the only thing I was able to come up with, any help will be appreciated. thanks for making time to read my thread Code: <html> <head> <script type="text/javascript"> function validateit() { var number = document.myform.product_number.value; var charnum = number.length; if (number =="") alert("you must enter a product number, field cannot be empty"); else if (charnum < 12 || charnum > 12) alert("the product numbre has to be exactly 12 characters long"); else validate_number(number); } function validate_number(num) { var objRegEx = /^[a-z]+$/; split=num.split("-",3); if (split[0].length!=3) alert("the Plant Code portion of the Product Number has to be only three charactes long") if!(objRegEx.test(split[0]) alert("the Plant Code portion of the Product Number has to be letters only") } </script> <title>waldo's</title> <style type="text/css"> .heading{font-weigth:bold;text-align:center; font-family:"comic sans MS"} </style> </head> <body><form name="myform"> <table align="center" border="1" width="55%"> <caption style="font-family:'comic sans MS';font-size:26pt"> Waldos's WareHouse</caption> <tr class="heading"><td>Product Number</td><td>Plant Code</td><td>Production Run</td><td>Shift Number</td></tr> <tr><td><input type="text" name="product_number"></td><td><input type="text" name="plant_code" readonly></td><td><input type="text" name="production_run" readonly></td><td><input type="text" name="shift" readonly></td></tr> <tr><td><input type="button" value="Check Validity" onclick="validateit()"/></td><td align="right">Validation Date:</td><td colspan="2"><input type"text" size="47" readonly></td></tr> </table></form> </body> </html> Similar TutorialsHey I'm trying to make a script which will check if the string which the user sent from a form contains ONLY letters. The problem is if the user entered something like this "25 years old" it allow that to be submitted. It only blocks submissions of the form if the user submits NO letters like this "12345". I want it to block submissions if at least one character isn't a letter. Here's my code: Code: var message = document.myform.formtest.value; var allowed = /[A-z+]/; if(!allowed.test(message)) { alert("The field only allows letters (a-z)."); return false; } Can someone please explain the following code to me!? I don't get regular expressions and how they work :S Code: function trim(string){ return string.replace(/^\s*/, "").replace(/\s*$/, ""); } Thanks! Hello. So I have been doing some regex in php. In Javascript i need to parse a url and replace ALL the & with \/%26 (or what ever that one is) and replace ALL the + with the % thingy. But my problem is I am doing url.replace(/&/,'\/%26') but what is happening is it is replace only the FIRST &. How can I do it to replace ALL &? I was thinking of doing some type of loop but for some reason nothing is working...THANKS IN ADVANCE! Hi everyone, I am trying to validate a date by using regular expressions. I have parts working, such as only accepts numbers, but I cannot get the range correct. On the "mm" field, I am getting errors. Code: if(form.mm.value=="") { alert("Please insert your birth month"); return false;} var re=/^(0[1-9]|1[0-2]){2}$/; if(!re.test(form.mm.value)) { alert("Please fix birth month!"); return false; } { if(form.dd.value=="") { alert("Please insert your birth day"); return false;} var re=/^\d{2}$/; if(!re.test(form.dd.value)) { alert("Please fix birth day!"); return false; } { if(form.yyyy.value=="") { alert("Please insert your birth year"); return false;} var re=/^\d{4}$/; if(!re.test(form.yyyy.value)) { alert("Please fix birth year!"); return false; Any suggestions will be greatly appreciated. Dear Experts I have folloiwng codes Code: <html> <head> <body> <center> <script language="JavaScript"> function checkpostal(){ var re=/^\D{A-Z}$/ if (myform.myinput.value.search(re)==-1) { alert("Good") }else{ alert("Bad") } } </script> <form name="myform"> <input type="text" name="myinput" size=15> <input type="button" onClick="checkpostal()" value="check"> </form> </center> </body> </html> With Onclick, I want to test input through regular expression If entered values is between a-z or A-Z then it must display alert("Good") else alert("Bad") Please help How can I get price from a string using regular expression ? Or by any other means . Let's say. var str="Our shop receives only $. This shoe costs $200. We don't accept anything else then $"; How could I retrieve '$200' from this above string. By any means. Thank you... Hi All I need help with javascript regular expressions. I have a text box in which user can enter only 4 types of values. 1) Varchar(n) where 0 < n <=80. Ex: Varchar(20) (Varchar(n) . 0< n<= 80 means he can enter values onlly like varchar(1) or varchar(2) ..... varchar(80) ) 2) Char(n) where 0 < n <=80. Ex: Char(20) 3) numeric(x,y) where x>y and 1<= x <=35 and 0<= y <=15. Ex: numeric(20,6) If the text box value doesnot match this pattern, we should throw him alert message. Thanks in Advance Hi, i'm new to javascript, im managing to find out how to do most things, but i need to validate two paths. I want to know how to check whether path1 is a subpath of path2. e.g. 1: /files/stuff/mypics/anotherfolder/etc 2:/files/stuff/mypics i want to be able to return a boolean given whether i can move folder 1 in to folder 2 in this case yes. but if you swap them its a no. please help. oxide Hey everyone I am trying to match an email string that ends exactly with ".com". Here's what I have Code: var email = window.prompt("Enter your email", ""); var email_match = /[a-zA-Z1-9-_.]{3,}\@[a-zA-Z]{3,}\.(com)/ if (email_match.test(email)) alert("Email is Valid"); else alert("Email Invalid!"); the (com) also matches commm for some odd reason. What must I change in the code so that only emails ending with .com is valid? Thanks! Hi I've got two examples of using regular expressions one works and the other doesn't but they using exactly the same pattern and the same text only difference is - The example that works uses a form to get the patern and text, the other has the pattern hard coded. Any help will be greatly appreciated Works - Code: <html> <head> <title></title> <style type="text/css"> </style> <script type="text/javascript"> <!-- function frmTestClick() { var re = new RegExp(document.frmTest.regex.value,"gi"); if (document.frmTest.subject.value.match(re)) { alert("Successful match"); } else { alert("No match"); } } function demoShowMatchClick() { var re = new RegExp(document.frmTest.regex.value,"gi"); var m = re.exec(document.frmTest.subject.value); if (m == null) { alert("No match"); } else { var s = "Match at position " + m.index + ":\n"; for (i = 0; i < m.length; i++) { s = s + m[i] + "\n"; } alert(s); } } function demoReplaceClick() { var re = new RegExp(document.frmTest.regex.value, "gi"); document.frmTest.result.value = document.frmTest.subject.value.replace(re, document.frmTest.replacement.value); } //--> </script> </head> <body> <div id="content"> <form name="frmTest" id="frmTest" action="" method="post"> <p>Regexp: <input type="text" name="regex" value="</?(b|strong|font|span)\b(.|\n)*?>" size="50"></p> <p>Subject string: <input type="text" name="subject" value="<font>the quick brown fox jumped over <span>the</span> lazy dog</font>" size="50"></p> <p><input type="button" value="Test Match" onclick="frmTestClick()"> <input type="button" value="Show Match" onclick="demoShowMatchClick()"></p> <p>Replacement text: <input type="text" name="replacement" value="replaced" size="50"></p> <p>Result: <input type="text" name="result" value="click the button to see the result" size="50"></p> <p><input type="button" value="Replace" onclick="demoReplaceClick()"></p> </form> </div> </body> </html> Doesn't work??? Code: <html> <head> <title></title> <style type="text/css"> </style> <script type="text/javascript"> <!-- function stripHTML(sVal,bIgnoreBold){ var sPat="</?(b|strong|font|span)\b(.|\n)*?>",re = new RegExp(sPat,"gi"); if (sVal.match(re)) { alert("Successful match"); } else { alert("No match"); } return sVal.replace(re,""); } //--> </script> </head> <body> <div id="content"> <form name="frmTest" id="frmTest" action="" method="post"> <label>Body: </label><textarea name="txtBody" id="txtBody" rows="10" cols="60"><font>the quick brown fox jumped over <span>the</span> lazy dog</font></textarea><br><br> <input type="button" name="btnDoStrip" id="btnDoStrip" value="Do Strip" onclick="this.form.txtBody.value=stripHTML(this.form.txtBody.value,true);"> <input type="reset" name="btnReset" id="btnReset" value="Reset"> </form> </div> </body> </html> Cheers Al Hello everyone, I'm new to using regular expressions with javascript. I'm trying to search a string for instances of a substring with a particular prefix, followed by some numerical digits. So for instance my larger_string is: "This is a string ABCD12 EFGH124 ABCD76 EFGH90" And initially I want to find all substrings starting 'ABCD', with two following numerical digits. I can do it like this: var answer = larger_string.match(/ABCD\d\d/); But I'd really like to pass the 'ABCD' part in as a string itself, myString, as I'd then like to set myString to 'EFGH' and others, to repeat the search for those. I'm struggling with the syntax for creating a regular expression froma string. So I can do this: var reg = new RegExp("ABCD", "g"); but, this doesn't work: var reg = new RegExp("ABCD\d\d", "g"); and similarly I can do this: var myString = "ABCD"; var reg = new RegExp(myString, "g"); but, this doesn't work: var myString = "ABCD\d\d"; var reg = new RegExp(myString, "g"); What is it that I'm doing wrong here? Thank you I have a string of code like such: Code: <font color=black>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000</font><br><font color=black>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000</font><br><font color=black>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000</font><br><font color=black>000000000000000000000000000000000000000000000</font><font color=white>0000</font><font color=black>000000000000000000000000000000000000000000000</font><br><font color=black>000000000000000000000000000000000000</font> except much longer, like... 4000 lines longer. What I want to do is go through this code and replace all the zeros between <font color=black> and </font> with 1's and leave anything between <font color=white> and </font> as 0's. I just really need the regular expression not the code. I started reading a book on regular expressions and it's like... 300 pages, so it would be nice to solve this problem now, rather than have to wait to finish the book to solve this. Hopefully when I'm done reading it will make sense, but can someone help me in the meantime? Hi I have finally figured how to search a text area for URL's... as below, then reformat so they are clickable links. It works!! But it looks so so messy, is there a better way to do this?? Code: var textNodeLinks = document.getElementById("comments"); textNodeLinks.innerHTML = textNodeLinks.innerHTML.replace(/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/g, "$1<a href=http://$2$3\ rel="nofollow" target=_blank>$2$3</a>"); textNodeLinks.innerHTML = textNodeLinks.innerHTML.replace(/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/g, "$1$2<a href=\"$3\" rel="nofollow" target=_blank>$3</a>"); Cheers Hi, can anyone tell me how to detect any word (a-z only, surrounded by whitespace) less than 5 letters long? Edit - this is what I have currently: Code: var RE=/\s([a-z]{1,4})\s/gi; var string="some words"; //should be turned to "words" string=string.replace(RE, ""); This is taking 4 letter chunks from the end of words. Cheers, Gus Edit - fixed (replaced \s with \b) Hello all, I have a form that submits a POST request when data is submitted. A Servlet then processes this POST request and a JavaBean is used to make some calculations. The HTML response is not generated within the Servlet but instead I forward the request to a JSP to generate the response. - This all works fine, thankfully. However, I am stupidly suck trying to validate the form on the client side with a JavaScript function before the form is submitted. Here is my index.jps: Code: <%-- Document : index Created on : 19-Nov-2009, 13:41:30 Author : lk00043 --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/JavaScript"> <!-- Start hiding JavaScript Statements function validateForm() { var student; var score1, score2, score3, score4; student = document.getElementById('student'); s1 = document.getElementById('score1'); s2 = document.getElementById('score2'); s3 = document.getElementById('score3'); s4 = document.getElementById('score4'); score1 = parseInt(s1.value); score2 = parseInt(s2.value); score3 = parseInt(s3.value); score4 = parseInt(s4.value); if(student.value.length == 0) { document.getElementById('StudentError1').innerHTML = " Enter a student name!"; return false; } if ((isNaN(score1)) || (score1 < 0) || (score1 > 100)) { document.getElementById('Error1').innerHTML = " Enter a number between 0 and 100!"; return false; } if ((isNaN(score2)) || (score2 < 0) || (score2 > 100)) { document.getElementById('Error2').innerHTML = " Enter a number between 0 and 100!"; return false; } if ((isNaN(score3)) || (score3 < 0) || (score3 > 100)) { document.getElementById('Error3').innerHTML = " Enter a number between 0 and 100!"; return false; } if ((isNaN(score4)) || (score4 < 0) || (score4 > 100)) { document.getElementById('Error4').innerHTML = " Enter a number between 0 and 100!"; return false; } } // End hiding JavaScript Statements --> </script> <title>Lab Class 7 - Task 2</title> </head> <body> <h1>Lab Class 7</h1> <form name="collectgrades" action="AssessGrades" method="POST" onSubmit="validateForm()" > Name of Student: <input type="text" name="student" id="student"/><span id="StudentError1"> </span><br /> Presentation: <input type="text" name="score" id="score1"/><span id="Error1"> </span><br /> Writing style: <input type="text" name="score" id="score2"/><span id="Error2"> </span><br /> Technical content: <input type="text" name="score" id="score3"/><span id="Error3"> </span><br /> Depth of analysis: <input type="text" name="score" id="score4"/><span id="Error4"> </span><br /> Feedback:<select name="feedback" size="4" multiple="multiple"> <option>"Could be better structured."</option> <option>"Depth of analysis is good."</option> <option>"Very advanced material."</option> <option>"Very well structured."</option> </select><br /> <input type="submit" value="Submit" /> </form> </body> </html> Regardless of whether incorrect input is given, the data is still POSTed to the server and calculated on or a Server Side error is given. Am I correct in calling the function onClick? The validation essentially needs to be so that: - Student field contains a string - Score1, Score2, Score3 and Score 4 contain a number between 0 and 100 Any help is most appreciated, Cheers, Beetle. I searched the forum for an answer to this question, but found nothing that was able to answer my question. I have a form and I need to validate a field against three rules: 1) The field need to be between 6 and 12 characters 2) It can only have letters, numbers, and the underscore 3) It cannot contain a space or other special characters I want the validate to happen in real-time. I have the first rule working great. Here is the code for that: Code: var username = document.getElementById('registerUsername'); if((username.value.length < 6) || (username.value.length > 12)) { document.getElementById('usernameValidate').innerHTML="Incorrect."; }else{ document.getElementById('usernameValidate').innerHTML="Correct."; } How would I be able to incorporate checking for rules 2 and 3? Hi all, I'm trying to change our shopping cart code by making a small modification. When editing a product, there is a dimensions box which currently only allows numbers. We want it to allow numbers and letters (don't ask why). The code we have is the following which we think is related to why our shopping cart won't allow letters in the box. Could someone please edit the following code to allow letters? Thank you. Code: if(isNaN(dimensionsFormat(prodWidth.value)) && prodWidth.value != "" && !sellingDP) { ShowTab(0); alert("%%LNG_EnterWidth%%"); prodWidth.focus(); prodWidth.select(); return false; } if(isNaN(dimensionsFormat(prodHeight.value)) && prodHeight.value != "" && !sellingDP) { ShowTab(0); alert("%%LNG_EnterHeight%%"); prodHeight.focus(); prodHeight.select(); return false; } if(isNaN(dimensionsFormat(prodDepth.value)) && prodDepth.value != "" && !sellingDP) { ShowTab(0); alert("%%LNG_EnterDepth%%"); prodDepth.focus(); prodDepth.select(); return false; } I am trying to make a JavaScript chat-bot I was using this to answer a month questions and it worked fine for what is the month after DatesA=new Array("january,February","february,March","march,April","april,May","may,June","june,July","july,Aug ust","august,September","september,October","october,November","november,December","december,January "); if (input.search("what is the next month after")!= -1) {document.result.result.value = "Sorry, I don't know."; for (i=0; i<DatesA.length; i++) { Date=DatesA[i].split('='); if (input.search(Date[0]) != -1) { document.result.result.value = Date[1];} } return true;} What is the month after May answer: June however it didn't with letters. Is there a way to write this to prevent the wrong single letter and small words from triggering Letterbefore=newArray("b=a","c=b","d=c","e=d","f=e","g=f","h=g","i=h","j=i","k=j","l=k","m=l","n=m", "o=n","p=o","q=p","r=q","s=r","t=s","u=t","v=u","w=v","x=w","y=x","z=y"); Then use this: if (input.search("what is the letter before")!= -1 || input.search("what letter comes before")!= -1) {document.result.result.value = "Sorry."; for (i=0; i<Letterbefore.length; i++) { Letter=Letterbefore[i].split('='); if (input.search(Letter[0]) != -1) { document.result.result.value = Letter[1];} } return true;} . The bot correctly answers for x y and z . It then answers V for all other letters, digits and short words What is the letter before cow answer: V Thank you for your time Hey everyone Okay so... I'm working on a site, which will include a registration form for users that wish to register. In this registration form I would like it to have an AJAX based effect, such that when the user types each letter out for his username in the field, his username will appear (letter upon letter) itself below, at the end of their unique url. To explain further:- Say I type my username to be Owen Below the field I would like it to display: http://www.mydomain.com/Owen http://Owen.mydomain.com/ As I type it. Is this possible? I've done my research, but had little luck. I'm sure it is possible as I've seen it before in a slightly different manner. Hope you can or are willing to help Thank you Owen Ayres |