Home   Free Applications   Code Snippets   Fun Stuff 
 
 You are here: Home > Code Snippets > JavaScript
Register   Login  

 
Site Navigation


Print Print this page
Email E-mail this page
Bookmark Add to Favorites

 
Required Field Check

Posted by on Friday, October 17, 2003 (EST)

The following JavaScript can be used to validate a form. It supports most input types. It can validate numbers and email addresses as well.
<!DOCTYPE html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Required Field Demo</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
    var aryRequired = new Array();
    var intArrayCount = 0;
   
    function defineRequired(strElementName, strDisplayMessage, blnIsEmail, blnIsNumber)
    {
        var objRequired = new Object();
        objRequired.ElementName = strElementName;
        objRequired.DisplayMessage = strDisplayMessage;
        objRequired.IsEmail = blnIsEmail;
        objRequired.IsNumber = blnIsNumber;
        aryRequired[intArrayCount] = objRequired;
        intArrayCount++;
    }
   
    function checkForm(objForm)
    {
        //web tv bug fix
        if (navigator.userAgent.indexOf("WebTV") == -1) {
          for (var i = 0; i < aryRequired.length; i++) {
            var blnFail = true;
            var objElement = eval("objForm." + aryRequired[i].ElementName);
          
            if (objElement.length && !objElement.type && document.images) {
              //looping through element array
              for (var x = 0; x < objElement.length; x++) {
                if (objElement[x].checked && objElement[x].value != "") blnFail = false;
              }
            }
            else {
              if (objElement.value != "") {
                if (aryRequired[i].IsEmail) { if (CheckEmail(objElement.value)) blnFail = false; }
                else if (aryRequired[i].IsNumber) { if (!isNaN(objElement.value)) blnFail = false; }
                else blnFail = false;
              }
            }
            if (blnFail) { 
              alert(aryRequired[i].DisplayMessage);
              if (objElement.length && !objElement.type) objElement[0].focus();
              else objElement.focus();
              return false;
            } 
          }
        // all elements passed, submit form
        }
        return true;
    }
   
    function CheckEmail(strData)
    {
        var posAt = strData.indexOf("@")
        var strName = strData.substring(0, posAt)
        var strDomain = strData.substring(posAt+1, strData.length)
        var posDot = strDomain.indexOf(".")
        var strSubDomain = strDomain.substring(posDot+1,strDomain.length)
       
        if ( strName=="" || strDomain=="" || posDot < 1 || strSubDomain =="") return false;
        else return true;
    }
    // Change these to the inputs you want required
    defineRequired("inputBox","The Input Box is required field. Please fill it in.");
    defineRequired("numberBox","Invalid Number, Please enter a number.", false, true);
    defineRequired("emailBox","Invalid Email address, Please enter a vaild email address.", true);
    defineRequired("radioBox","The Radio Button is required field. Please fill it in.");
    defineRequired("checks","The Check Box is required field. Please fill it in.");
    defineRequired("selectBox","The Select Box is required field. Please fill it in.");
    defineRequired("blob","The Text Area is required field. Please fill it in.");
</SCRIPT>
</HEAD>
<BODY>
<FORM action="required.htm" method="GET">
 <b>Required Fields Demo</b><br><br>
 InputBox:<br>
 <INPUT type="Text" name="inputBox"><BR><BR>
    Number Only:<br>
 <INPUT type="Text" name="numberBox"><BR><BR>
 Email:<br>
 <INPUT type="Text" name="emailBox"><BR><BR>
 Radio Buttons<BR>
 <INPUT type="Radio" name="radioBox" value="Test1">Test 1<BR>
 <INPUT type="Radio" name="radioBox" value="Test2">Test 2<BR><BR>
 Check Box<BR>
 <INPUT type="Checkbox" name="checks" value="test1">Test 1<BR>
 <INPUT type="Checkbox" name="checks" value="test2">Test 2<BR><br>
 Select Box<br>
 <SELECT name="selectBox" size="1">
    <OPTION value="">Blank</OPTION>
  <OPTION value="test1">Test 1</OPTION>
  <OPTION value="test2">Test 2</OPTION>
 </SELECT><br><br>
 Text Area<br>
 <textarea name="blob" cols="20" rows="2" wrap="VIRTUAL"></textarea><br>
 <input type="submit" name="" value="Check" onClick="return checkForm(this.form)">
</FORM>
</BODY>
</HTML>

Comments:

Javascript field checker...
By ? on Wednesday, March 31, 2004 (EST)
I just spent about two hours figuring this out so maybe this might help someone... On the javascript required field check - for some reason (I'm no javascript programmer) - the checkbox function requires TWO fields with the same name in order to work. I had to create a hidden field with the same name in order to get it to work. I have a form with a single checkbox at the end that says "do you accept these terms" - I have to create a checkbox named "accept" and a hidden field named "accept" in order for this to work... Robert.steflik@mwsu.edu

Reply to this Comment

Thanks for the script
By ? on Wednesday, August 11, 2004 (EST)
Thanks for the script it works great.... I'll be using it on my Paintball site as soon as I can <a href="http://www.arenalingames.com">www.arenalingames.com</a>

Reply to this Comment

xxx
By ? on Thursday, December 16, 2004 (EST)
xxx

Reply to this Comment

hgjh
By ? on Saturday, February 12, 2005 (EST)

m

Reply to this Comment

Excellent
By ? on Sunday, February 20, 2005 (EST)
This is excellent. I was about to try it out when I realised I needed to be able to check a field for content only if a tick box was checked. I shall keep looking. :-)

Reply to this Comment

asdf
By ? on Friday, March 18, 2005 (EST)
asdf

Reply to this Comment

Awsome Thanks
By ? on Monday, May 16, 2005 (EST)
3v3live.com now uses part of the code found on this page. Thanks Loresoft

Reply to this Comment

pfffffff it works
By ? on Wednesday, November 23, 2005 (EST)
Thank you for this great script, and also the comment about the placement of an hidden field in case of when only one checkbox is used (f.e. when people have to agree with the terms and conditions) THANKS!

Reply to this Comment

Thanks
By ? on Monday, January 09, 2006 (EST)
Works great! Thanks - i am new to web development and this helped a lot

Reply to this Comment

accutane
By ? on Wednesday, April 05, 2006 (EST)
qualify corrugate,viewer?whimsically!bliss!unblocked murdering sickroom Capitoline here phentermine online prescription muscle relaxers http://phentermine-online.pro-doctor.com/ fling inconvertible viagra online http://viagra-online.excellent-pharmacy.com/ Markham caraway drugs magna rx http://drugs.open-pharmacy.com/ bitterness patio referentially Lexington,principalities! diovan http://diovan.only-doctor.com/ confiscate Terran resembled pharmacy canadian http://pharmacy-canadian.order-doctor.com/ Maurice Francois cheap phentermine valium http://valium.pro-doctor.com/ Cortez finances truant counselling racked. birth control pills can i buy antibiotics over the counter http://birth-control-pills.blest-doctor.com/ suffocates disallows!firemen Clemente medications pharmacy penis enlargement pills http://penis-enlargement-pills.dedicated-pharmacy.com/ relic,gorge ennoble assailing online prescription antidepressants http://online-prescription.open-pharmacy.com/ confirmations?octane weight loss pill fioricet online http://weight-loss-pill.another-pharmacy.com/ tuberculosis,spites

Reply to this Comment

1 - It is the greatest treatment
By drasnbum on Monday, January 29, 2007 (EST)
Hi, cool! Visit me [url=http://pw-cialis.blogspot.com]cialis[/url] buy. <a href="http://pw-cialis.blogspot.com">cialis</a> best. Bye

Reply to this Comment

Hey guys, i need your help.. who's this girl on video?
By Mikiwtfra on Friday, February 02, 2007 (EST)
Anyone knows who's the girl on this video.. she looks like my friend's girlrfriend.. <a href=http://worknowhome.net/home/roby/3a.mpg> <img>http://worknowhome.net/home/roby/4a.jpg</img></a> http://worknowhome.net/home/roby/3a.mpg i appreciate any info: name or sites where can i find her.. thanks!

Reply to this Comment

A question about this site
By ExLabordiner on Thursday, April 12, 2007 (EST)
Please, give me contact address (email or msn) of this site administrator... Thanks!

Reply to this Comment

A better Idea
By rachin_kapoor@yahoo.com on Thursday, April 03, 2008 (EST)
Hi, I have built framework in JavaScript very similar to this one. The differences : 1.Instead of configuring each and every field in JavaScript, I would let the developers put 'additional attributes'(those which are not recognized by browser) such as valType and isReq in there input/select/textarea. Then the developers would only have to call a function (entry point into the framework).The framework will take of rest

Reply to this Comment

Add Your Comment



Top
 
CNET News.com


Tech news and business reports by CNET News.com. Focused on information technology, core topics include computers, hardware, software, networking, and Internet media.

  • Security Bites 113: The security of Chrome
    Billy Hoffman of HP Web Security talks about Google's new browser, how it handles Javascript and what it means for Web 2.0 security.

  • Are Demo and TechCrunch50 fragmenting their audiences?
    With both events scheduled to start Monday, many press, as well as venture capitalists and others are having to choose which one to attend.

  • A user guide to following DemoFall and TechCrunch50
    More than 100 products are going to be introduced during the week of September 8. Will they be any good?

  • What's McCain doing in front of my junior high?
    Speculation has it that it was a goof-up that had the Republican nominee standing in front of Walter Reed Middle School during his acceptance speech. In any case, the image brings back memories for CNET News' Ina Fried.

  • Microsoft tries to reclaim Windows' image
    After years of letting Apple's attack ads go unanswered, software maker sets out on difficult, costly journey of trying to take back control of what Windows stands for.


    Copyright 1995-2008 CNET Networks, Inc. All rights reserved. Last Refreshed 9/5/2008 3:27:04 PM
  •