472,373 Members | 1,987 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,373 software developers and data experts.

Using regexp to validate simple form

I run a small camp in Alaska for kids and my director is asking for a web form. Could someone please have a look and offer some advice on where I'm making mistake(s)?
I'm using the RegExp function to validate 3 types of fields: text, radio button, dropdown menu. but the code doesn't validate. After 2 days, it's time I asked for guidence.
Text: only alphabet, no numerals, allowed
Radio: one must be selected,
Dropdown: an option must be selected.
Phone number: exactly 10 digits.
Email: can only come from domains: .com, .net, .gov, OR .edu (haven't yet asked 'why?' but that's what the director's asking for)

1. I don't want all the errors to come up inside one alert, but rather have one alert show at a time. After one entry error is corrected, the next error will appear after clicking submit again. For example, if the form is sent blank, ONLY the Alert, "Please enter your name." appears because it is the first field.

2. Once the form is completed correctly, an alert saying, "Thank you for completing the form." pops up in front of the new page which the SUBMIT button leads to.

I'm an advanced/beginner catching up on JS. The VAR for GENDER and CITY have been left empty on purpose, simply because I don't know how to enter the correct info.
There are other text fields and radio buttons in the full version of form so if I can get these validations to work, I'll be good to go with the others.
Thank you in advance for your insight.
Both the JS and HTML are given below.

<script language="javascript">
function validate (){
var fullname = document.module102form.fullname.value;
var gender = document.module102form.gender.value;
var country = document.module102form.city.value;
var email = document.module102form.email.value;

var fullnameRegExp=/\d/;
var genderRegExp=/ /;
var countryRegExp=/ /;
var emailRegExp=/^[@]||[.com]||[.net]||[.edu]||[.gov] /\g;

if (fullnameRegExp.test(fullname)!=true)
alert("Please reenter your FULL NAME.");
if (genderRegExp.test(gender)= unchecked)
alert("Please select a GENDER.");
if (countryRegExp.test(country)!=true)
alert("Please select a CITY.");
if (emailRegExp.test(email)!=true)
alert("Please valid EMAIL.");
else {

alert("Thanks for completing the form.");
<FORM METHOD="post" name="module102form" onSubmit="return validate(this);" ACTION="http://nova.crs.com/cgi-bin/cgiwrap/~em680a04/module102.php">
<!-- START HTML -->
<TD><INPUT NAME="fullname" TYPE="text"> </TD>
<TD><INPUT TYPE="radio" NAME="gender" VALUE="Male"> MALE <INPUT TYPE="radio" NAME="gender" VALUE="Female" > FEMALE </TD>
<TD><SELECT NAME="country">
<OPTION VALUE="select"> Please select a city</option>
<OPTION VALUE="anchorage"> Anchorage </option>
<OPTION VALUE="fairbanks"> Fairbanks</option>
<OPTION VALUE="juneau"> Juneau </option>
<TD><INPUT NAME="email" TYPE="text"> </TD>
<!-- BUTTON -->
Dec 4 '06 #1
11 7526
Hi! I made a few changes in you javascript code. I'm not sure what you wanted to check when it comes to fullname, but you checked if it did not contain a digit which I'm quite sure you didn't meen to :) Now it checks if it is a full name ( ex "chandler bing" or "chandler bing bong") not just "chandler".

Gender will actually return an array because there are two elements with same name. You have to check if either of them are checked.

contry.value will return "select" when no city is selected. I suppose that it should be city all the way.

validating an e-mail is hard, but this little regex just checks the end.

Expand|Select|Wrap|Line Numbers
  1. function validate () {
  2.     var fullname = document.module102form.fullname.value;
  3.     var country = document.module102form.country.value;
  4.     var email = document.module102form.email.value;
  6.     var fullnameRegExp=/^\D+( \D+)+$/;
  7.     var emailRegExp=/[.](com|net|edu|gov)$/;
  9.     if (!fullnameRegExp.test(fullname)) {
  10.         alert("Please reenter your FULL NAME.");
  11.         return false;
  12.     }
  14.     if (!document.module102form.gender[0].checked && !document.module102form.gender[1].checked) {
  15.         alert("Please select a GENDER.");
  16.         return false;
  17.     }
  19.     if (country == "select") {
  20.         alert("Please select a CITY.");
  21.         return false;
  22.     }
  24.     if (!emailRegExp.test(email)) {
  25.         alert("Please valid EMAIL."); 
  26.         return false;
  27.     }
  29.     alert("Thanks for completing the form.");
  30.     return true;
  31. }
Dec 4 '06 #2
Thank you. I'm dusting off my brain so the changes you made are clear.

So is this the correct onSubmit?
onSubmit="return validate(this);"
I'm not clear on the differences between
onSubmit="return validate(this);"
onSubmit="return validate_form();"
onSubmit="return validate();"
Could you explain which is best for this form(in simple terms)?
Dec 4 '06 #3
I'm sorry, I forgot to tell you.

As you can see the function is declared as "function validate()" which meens that functions name is validate and that it takes no arguments (the parentesis is empty). This meens that you should call it by validate(). validate() will return true or false. onsubmit should return what validate returns. I know that is sounds a little bit too much already, but onsubmit="return validate()" will to the job.

You are welcome to ask as many questions as you want :) Is there anything in the javascript function that puzzles you?
Dec 4 '06 #4
That clears it up and makes sense. Used onSubmit return validate (); and worked well.
One point I'm still vague on is this... for validations, when using

Expand|Select|Wrap|Line Numbers
  1. var fullname = document.feedback.fullname.value;// TEXT BOX
  2. var city = document.feedback.city.value;          // DROPDOWN 
  3. var gender = document.feedback.gender.value;      // DROPDOWN
  4. var area = document.feedback.area.value;     // TEXT BOX
  6. var fullnameRegExp=/^\D+( \D+)+$/;
  7. var emailRegExp=/[.](com|net|edu|gov)$/;
  8. var areaRegExp=/^[a-zA-z]+$ /;
  9. var cityRegExp=/ /;
  10. var phoneRegExp=/ /;
  11. var cellRegExp=/ /;
  12. var emailRegExp=/ /;.
Dec 4 '06 #5
(my 5 min of allowed 'edit' time expired so am posting a new reply)
Thank you. That makes sense and it works.
There is one point that I'm getting hung up on...using VAR in RegExp validations. For example here I use 4 fields, fullname, gender, city, and interests; each with a different input style.

var fullname = document.feedback.fullname.value; // TEXT BOX
var city= document.feedback.city.value; // DROPDOWN MENU
var interest = document.feedback.interest.value; // CHECKBOX
var gender = document.feedback.gender.value; // RADIO BUTTON

then in the next step, xxxRegExp is used for only TEXTBOX var's, such as
var fullnameRegExp=/^\D+( \D+)+$/;

If so then this leaves RADIO BUTTONS, DROPDOWN MENUS and CHECKBOXES to be validated later in the code, in a type of 'self-contained' (if that makes sense) expression. Such as

if (city == "select") {
alert("Please select a CITY.");
return false;

Am I thinking on the right track in why xxxRegExp is used for only some of the VAR's and not others?
Thank you.
Dec 4 '06 #6
Using regular expression to validate a select box is some what overkill.

Expand|Select|Wrap|Line Numbers
  1. <select name="s_city">
  2. <option value="">- Choose a city -</option>
  3. <option value="New York">New York</option>
  4. </select>
In this case the value of the select will be an empty string if the user didn't selected a city. You can decide what value it will get. You don't need a regular expression because the user simply can not choose something else.

When it comes to the area code you can use a regex. I don't know how such a code looks because I'm not american, but the example you gave would except everything from "a" to "aaaaafffffffffsssssssssdddddddddd".
Dec 4 '06 #7
Checkboxex and radio buttons are a different story. They are checked.

If you have a checkbox you just check if it's checked.

Expand|Select|Wrap|Line Numbers
  1. if (document.myform.mycb.checked)
  2. do something;
With radio buttons you get the an array with all radio button with the same name. Unless it's just one, then it will work just like a checkbox.

Expand|Select|Wrap|Line Numbers
  1. <input type="radio" name="car">BMW
  2. <input type="radio" name="car">Mercedes
  3. <input type="radio" name="car">Jaguar
  5. if (document.myform.car[0].checked) // you have a bmw
  6. if (document.myform.car[1].checked) // you have a mercedes
  7. if (document.myform.car[2].checked) // you have a jaguar.
Dec 4 '06 #8
That makes sense. Thank you. I'll make a note of the radio button examples.
BTW I'm not american either. I just happen to live in Alaska for work...hopefully I'll be able to find a job in a warmer climate. :-)
Thank you for your help.
It is greatly appreciated.
Dec 5 '06 #9
You're welcome :) Warmer climate could work for me too :) I live in Sweden. Probably not as cold as Alaska, but not like Thailand either ;)
Dec 5 '06 #10
Tack själv.
Everying I've seen/read/heard about Sweden has been good. Very few countries can say that.
Can I ask one more question?
Using the two below VAR's, as examples, what script could I use to make sure the phone # and cell # are different? Alert appears if user enters the same # in both fields. (it's not a big issue, just want to learn more).

Thank you for taking the time to educate a lesser skilled person.
var phone = document.feedback.phone.value;
var cell = document.feedback.cell.value;

if (!phoneRegExp.test(phone)) {
alert("Please reenter your PHONE NUMBER.");
return false;
if (!cellRegExp.test(cell)) {
alert("Please reenter your CELL NUMBER.");
return false;

Dec 5 '06 #11
I'm glad that you think that Sweden might be a good place to be :)

This little snippet of code will validate the number and check if they're identical. I was assuming that a phone # can start with "+".

Expand|Select|Wrap|Line Numbers
  1. function checkPhones() {
  2.     var reNumber = /^[+]?\d+$/;
  3.     var vPhone = document.getElementById("t_phone").value;
  4.     var vCell = document.getElementById("t_cell").value;
  6.     if (!reNumber.test(vPhone)) {
  7.         alert("Not valid Phone Number");
  8.         return;
  9.     }
  10.     if (!reNumber.test(vCell)) {
  11.         alert("Not valid Cell Phone Number");
  12.         return;
  13.     }
  14.     if (vPhone == vCell) {
  15.         alert("The numbers are identical");
  16.         return;
  17.     }
  19.     alert("They're good");
  20. }
Dec 5 '06 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Lukas Holcik | last post by:
Hi everyone! How can I simply search text for regexps (lets say <a href="(.*?)">(.*?)</a>) and save all URLs(1) and link contents(2) in a dictionary { name : URL}? In a single pass if it could....
by: Andrew DeFaria | last post by:
I was reading my O'Reilly JavaScript The Definitive Guide when I came across RegExp and thought I could tighten up my JavaScript code that checks for a valid email address. Why does the following...
by: Dag Sunde | last post by:
My understanding of regular expressions is rudimentary, at best. I have this RegExp to to a very simple validation of an email-address, but it turns out that it refuses to accept mail-addresses...
by: Bill McCormick | last post by:
Hello, I'm new to VB.NET but have used regexp in Perl and VI. I'd like to read a regular expression from a file and apply it to a string read from another file. The regexp is simple word...
by: c676228 | last post by:
Hi everyone, I just realized that it's so important to validate each string, I mean 'each' before you insert data from asp page into database. I guess some customers just copy data from some...
by: samuelberthelot | last post by:
Hello, I would like to validate a date in a textbox on the onChange event. The date must be in the format 01/01/2007 I would like to use a regular expression to validate it but I'm not very...
by: KevinADC | last post by:
Note: You may skip to the end of the article if all you want is the perl code. Introduction Uploading files from a local computer to a remote web server has many useful purposes, the most...
by: Ben Amada | last post by:
Hi all. I know very little about regular expressions, but wanted to use one to validate an email address a user would be entering before the form is submitted. There are many examples out there. ...
by: Mohammad Abou-Basha | last post by:
Hello, I've just posted a snippet on JavaScript RegExp, it's still a stub http://www.wikicodia.com/wiki/JavaScript_Regular_expression Please help me to expand it and put all information about...
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.
by: DizelArs | last post by:
Hi all) Faced with a problem, element.click() event doesn't work in Safari browser. Tried various tricks like emulating touch event through a function: let clickEvent = new Event('click', {...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.