SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Enthusiast darkhorse162's Avatar
    Join Date
    Oct 2006
    Location
    Duluth, MN
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Help! javascript form validation

    I am trying to validate a very simple contact form. I am using javascript client side validation so that it won't submit if there are any fields left blank, and it should also be validating the email address. I can't figure out why it's not working because I can leave all fields blank and it will still submit.

    I have the javascript in a separate file linked in the <head> of the page like so:
    <script type="text/javascript" src="js/form_validation.js"></script>

    ********************This is what 'form_validation.js' looks like:

    Code:
    <!--
    function isblank(s) {
    	for(var i = 0; i < s.length; i++) {
    		var c= s.charAt(i);
    		if ((c != ' ') && (c != '\n') && (c != '\t')) {
    			return false;
    		}
    	}
    	return true;
    }
    
    function verify(f) {
    	var msg;
    	var empty_fields = "";
    	var errors = "";
    	
    	for(var i = 0; i < f.length; i++) {
    		var e = f.elements[i];
    		if ((e.type == "text") || (e.type == "textarea")) {
    			// check to see if any fields are empty
    			if ((e.value == null) || (e.value == "") || (isblank(e.value)) {
    				empty_fields += "\n" + e.description;
    				continue;
    			}// end empty field check
    		
    			// validate email fields
    			if (e.email && !isblank(e.value)) {
    				var seenAt = false;
    				var append = "";
    				for(var j = 0; j < e.value.length; j++) {
    					var c = e.value.charAt(j);
    					if ((c == ' ') || (c == '\n') || (c == '\t')) {
    						append += "\n - not contatin white-space";
    					}
    					if ((c == '@') && (seenAt == true)) {
    						append += "\n - contain only on @";
    					}
    					if ((c == '@')) {
    						seenAt = true;
    					}
    				}
    				if (seenAt == false) {
    					append += "\n - contain exactly one @";
    				}
    				if (append) {
    					errors += "- The field " + e.description + "must: " + append;
    				}
    			}// end validate email
    		}// end if text or textarea
    	}// end for
    	// display any error messages if any exist
    	if (!empty_fields && !errors) {
    		return true;
    	}
    	msg = "-------------------------------------------------------------\n\n";
    	msg += "The form was not submitted because of the following error(s).\n";
    	msg += "Please correct these error(s) and re-submit.\n";
    	msg += "-------------------------------------------------------------\n\n";
    	if (empty_fields) {
    		msg += "- The following required field(s) are empty: " + empty_fields + "\n";
    		if (errors) {
    			msg += "\n";
    		}
    	}
    	msg += errors;
    	alert(msg);
    	return false;
    }
    // -->
    *************************Now here is my form:

    HTML Code:
    <form onsubmit="this.name.description='Name';this.email.description='Contact Email';this.email.email=true;this.comments.description='Comments';return verify(this);" action="thankyou.php" method="post">
    <table cellpadding="2" cellspacing="0" class="Common_Tables_Header" style="margin-top: 0px;">
    	<tr class="table_row3">
    		<td valign="top">
    			Name:
    		</td>
    	</tr>
    	<tr class="table_row3">
    		<td valign="top" style="padding-left: 25px;">
    			<input type="text" name="name" style="width: 200px;" />
    		</td>
    	</tr>
    	<tr class="table_row3">
    		<td valign="top">
    			Contact Email:
    		</td>
    	</tr>
    	<tr class="table_row3">
    		<td valign="top" style="padding-left: 25px;">
    			<input type="text" name="email" style="width: 200px;" />
    		</td>
    	</tr>
    	<tr class="table_row3">
    		<td valign="top">
    			Comments:
    		</td>
    	</tr>
    	<tr class="table_row3">
    		<td valign="top" style="padding-left: 25px;">
    			<textarea name="comments" rows="6" style="width: 500px;overflow: auto;"></textarea>
    		</td>
    	</tr>
    	<tr class="table_row3">
    		<td valign="top">
    			<input type="hidden" name="form_type" value="contact" />
    			<input type="submit" value="Submit" />
    		</td>
    	</tr>
    	</tr>	
    </table>
    </form>
    ***********************Can anyone help me out? Thanks!
    Last edited by darkhorse162; Oct 14, 2006 at 23:44. Reason: spelling
    .:::darkhorse162:::.

  2. #2
    SitePoint Wizard
    Join Date
    Mar 2004
    Posts
    1,647
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i dont understand your first loop in verify function...
    on which data is based?

    is beeter to keep stuff simple...

    cheers

  3. #3
    SitePoint Enthusiast darkhorse162's Avatar
    Join Date
    Oct 2006
    Location
    Duluth, MN
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The first loop should be looping through each of the fields in the form.

    verify(f) is called in the form as verify(this)...

    I agree with keeping things simple, this is just a script I found for error checking in a book I have. I believe it is more applicable for more lengthy forms with more error checking. Do you have any better suggestions for a simpler solution? I just want to make sure all fields are filled out and the email is correct(and only 1 email) Thanks for the reply.
    .:::darkhorse162:::.

  4. #4
    SitePoint Enthusiast darkhorse162's Avatar
    Join Date
    Oct 2006
    Location
    Duluth, MN
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Anyone?
    .:::darkhorse162:::.

  5. #5
    SitePoint Addict darkwater23's Avatar
    Join Date
    Nov 2005
    Location
    Omaha, NE
    Posts
    335
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Dreamweaver FTW! The following prevents the form from posting if the fields are blank or if an invalid email address is entered. This code was generated by Dreamweaver and is cross-browser friendly.

    DW Javascript:

    Code:
    <script language="JavaScript" type="text/JavaScript">
    <!--
    function MM_findObj(n, d) { //v4.01
      var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
      if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
      for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
      if(!x && d.getElementById) x=d.getElementById(n); return x;
    }
    
    function MM_validateForm() { //v4.0
      var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
      for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
        if (val) { nm=val.name; if ((val=val.value)!="") {
          if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
            if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
          } else if (test!='R') { num = parseFloat(val);
            if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
            if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
              min=test.substring(8,p); max=test.substring(p+1);
              if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
        } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
      } if (errors) alert('The following error(s) occurred:\n'+errors);
      document.MM_returnValue = (errors == '');
    }
    //-->
    </script>

    The form (note the changes):

    Code:
    <form action="thankyou.php" method="post" onSubmit="MM_validateForm('name','','R','email','','RisEmail','comments','','R');return document.MM_returnValue">
      <table cellpadding="2" cellspacing="0" class="Common_Tables_Header" style="margin-top: 0px;">
        <tr class="table_row3">
          <td valign="top"> Name: </td>
        </tr>
        <tr class="table_row3">
          <td valign="top" style="padding-left: 25px;"><input type="text" name="name" style="width: 200px;" />
          </td>
        </tr>
        <tr class="table_row3">
          <td valign="top"> Contact Email: </td>
        </tr>
        <tr class="table_row3">
          <td valign="top" style="padding-left: 25px;"><input type="text" name="email" style="width: 200px;" />
          </td>
        </tr>
        <tr class="table_row3">
          <td valign="top"> Comments: </td>
        </tr>
        <tr class="table_row3">
          <td valign="top" style="padding-left: 25px;"><textarea name="comments" rows="6" style="width: 500px;overflow: auto;"></textarea>
          </td>
        </tr>
        <tr class="table_row3">
          <td valign="top"><input type="hidden" name="form_type" value="contact" />
            <input type="submit" value="Submit" />
          </td>
        </tr>
        </tr>
        
      </table>
    </form>
    Enjoy!

  6. #6
    SitePoint Enthusiast darkhorse162's Avatar
    Join Date
    Oct 2006
    Location
    Duluth, MN
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you so much darkwater, I will try this and let you know how it works.
    .:::darkhorse162:::.

  7. #7
    SitePoint Enthusiast darkhorse162's Avatar
    Join Date
    Oct 2006
    Location
    Duluth, MN
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yep, it works just fine, thanks again!
    .:::darkhorse162:::.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •