Jump to content

[SOLVED] architecturalinstallationteam.com onsubmit validation problem


Revlet

Recommended Posts

My website at http://www.architecturalinstallationteam.com/index.php?p=contact_us has a minor glitch where the onsubmit form validation only works in IE for some reason!

 

 

PHP script to handle form preview and mailing:

 

<?php session_start();

//include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
//$securimage = new Securimage();

//if ($securimage->check($_POST['captcha_code']) == false) {
  // the code was incorrect
  // handle the error accordingly with your other error checking

  // or you can do something really basic like this
//  die('The code you entered was incorrect.  Go back and try again.');
//}

switch($_POST['view'])
{
case 1: /* first time submit, show preview */
   $type = "hidden";
   $vis_type = "none";
   $area_type = "absolute";
   $Name = $_POST['Name'];
   $Title = $_POST['Title'];
   $Company = $_POST['Company'];
   $Telephone = $_POST['Telephone'];
   $Email = $_POST['Email'];
   $Message = $_POST['Message'];
   $view = 2;
   
if(($_SESSION['security_code'] == $_POST['security_code']) && (!empty($_SESSION['security_code'])) )
{
    //CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
$EXTRA_INFO = "<div id='container'>
<strong>Are your sure you want to submit:</strong>
   <div id='left'>
   <p>Name:</p>
   <p>Title:</p>
   <p>Company:</p>
   <p>Telephone:</p>
   <p>Email:</p>
   <p>Message:</p>
   </div><!-- left -->
  <div id='right'>
   <p>$Name</p>
   <p>$Title</p>
   <p>$Company</p>
   <p>$Telephone</p>
   <p>$Email</p>
   <p>$Message</p>
  </div>
  <!-- right -->
  <div class='clear'></div>
</div><!-- container -->";
}
else {
echo "<strong><p style='color: #CC0000'>The code you entered was incorrect.</strong>";
}
   

   $FORM = "";

if(($_SESSION['security_code'] == $_POST['security_code']) && (!empty($_SESSION['security_code'])) )
{
    //CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
$INPUT_BUTTON = "<input type='submit' value='Edit' name='submit' id='submit_button' /> <input type='submit' value='Send' name='submit' id='submit_button' />";
}
else {
echo "  Please go back and try again.</p>";
$INPUT_BUTTON = "<div style='text-align: center;'><input type='submit' value='Edit' name='submit' id='submit_button' /></div>";
}


   ;
   break;
case 2: /* second time submit, if edit pressed, then edit else submit */
   if($_POST['submit'] == "Edit")
     { /* Edit and reset to first time here */
       $Name = $_POST['Name'];
   $Title = $_POST['Title'];
   $Company = $_POST['Company'];
   $Telephone = $_POST['Telephone'];
   $Email = $_POST['Email'];
   $Message = $_POST['Message'];
       $type = "text";
   $vis_type = "block";
   $area_type = "";
       $view = 1;
       $INPUT_BUTTON = "<img src='captcha/CaptchaSecurityImages.php' alt='captcha image' /><br />
   						Please enter the five characters:  <input id='security_code' name='security_code' type='text' maxlength='5' /><br /><br />
   					<input type='submit' value='Preview' name='preview' id='submit_button' />";
   //$FORM = "<form action='$PHP_SELF' method='post'>
   //		<input type='$type' name='0' size='4' value='Name:'>
   //		<input type='hidden' value='$view' name='view'>
   //		<input type='$type' name='Name' value='$Name'><br>";
       $EXTRA_INFO = "<strong>Edit Message:</strong><br />";
     }
   else
     { /* Submit info */
// Get POST variables
$EmailFrom = "AIT Website";
$EmailTo = "scott.bryant@aiteampro.com";
$Subject = "AIT Website - Contact Requested";
$Name = Trim(stripslashes($_POST['Name'])); 
$Title = Trim(stripslashes($_POST['Title'])); 
$Company = Trim(stripslashes($_POST['Company'])); 
$Telephone = Trim(stripslashes($_POST['Telephone'])); 
$Email = Trim(stripslashes($_POST['Email'])); 
$Message = Trim(stripslashes($_POST['Message'])); 

// Create Email
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Title: ";
$Body .= $Title;
$Body .= "\n";
$Body .= "Company: ";
$Body .= $Company;
$Body .= "\n";
$Body .= "Telephone: ";
$Body .= $Telephone;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// Send Email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// Redirect 
if ($success){
  //print "<meta http-equiv=\"refresh\" content=\"0;URL=index.php?p=sent\">";
include('include/sent.php');
$type = "hidden";
$vis_type = "none";
$area_type = "absolute";
}
else{
include('include/error.php');
$type = "hidden";
$vis_type = "none";
$area_type = "absolute";
  //print "<meta http-equiv=\"refresh\" content=\"0;URL=index.php?p=error\">";
//$EXTRA_INFO = "Error! Message not successfully sent.<br><pre>$Name</pre>";
//$type = "hidden";
//$vis_type = "none";
}

}
   break;
default: /* either we've never been here or something has screwed our counter */
   $EXTRA_INFO = "<strong>Enter information below:</strong><br />";
   $INPUT_BUTTON = "<img src='captcha/CaptchaSecurityImages.php' alt='captcha image' /><br />
   					Please enter the five characters:  <input id='security_code' name='security_code' type='text' maxlength='5' /><br /><br />
				<input type='submit' value='Preview' name='preview' id='submit_button' />";
   $type = "text";
   $vis_type = "block";
   $area_type = "";
   $view = 1;
   break;
}
/* display our page accordingly */

echo $EXTRA_INFO;
echo "<form action=\"$PHP_SELF?p=contact_us\" method=\"post\" onsubmit=\"MM_validateForm('Name','','R','Title','','R','Company','','R','Email','','RisEmail');return document.MM_returnValue\">
<div id='container'>
<div id='left' style='display: $vis_type'>
   <p>Name:</p>
   <p>Title:</p>
   <p>Company:</p>
   <p>Telephone:</p>
   <p>Email:</p>
   <p>Message:</p>
</div><!-- left -->
  <div id='right' style='display: $vis_type'>
<input type='hidden' value='$view' name='view' />
<input type='$type' name='Name' value='$Name' size='50' /><br />
    
    <input type='hidden' value='$view' name='view' />
    <input type='$type' name='Title' value='$Title' size='50' /><br />
   
    <input type='hidden' value='$view' name='view' />
<input type='$type' name='Company' value='$Company' size='50' /><br />
    
    <input type='hidden' value='$view' name='view' />
<input type='$type' name='Telephone' value='$Telephone' size='50' /><br />
    
    <input type='hidden' value='$view' name='view' />
<input type='$type' name='Email' value='$Email' size='50' /><br />
    	
<textarea name='view' cols='113' rows='8' style='position: absolute; visibility: hidden'>$view</textarea>
<textarea name='Message' cols='113' rows='8' style='position: $area_type; visibility: $type'>$Message</textarea><br />
  </div><!-- right -->
  <div class='clear'></div>
</div><!-- container -->";
echo "<div style='text-align: right;'>$INPUT_BUTTON</div>";
echo "</form>";

?> 

 

And the javascript to validate form onsubmit:

 

<!--
function MM_validateForm() { //v4.0
  if (document.getElementById){
    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=document.getElementById(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 == '');
} }
//-->

 

 

Any help is greatly appreciated as this is the last glitch to workout before site is complete!

 

Thanks,

Revlet

 

Link to comment
Share on other sites

  • Replies 52
  • Created
  • Last Reply

Top Posters In This Topic

Well, it's very... extensive. What is it you're trying to validate? The entire form or what?

 

Name, Title, Company, Email.

 

The code below is how the javascript is supposed to handle the submission and check that email is email and the others simply have text.

 

onsubmit="MM_validateForm('Name','','R','Title','','R','Company','','R','Email','','RisEmail');return document.MM_returnValue"

 

 

Do you have an idea of what might be going on or how to fix it?

Link to comment
Share on other sites

No, it's too big of a mess. I was thinking of re-writing it all. If you don't mind me asking, what are the validations for Name, Title, Company and Email?

 

 

What do you mean? Name, Title, and Company have to be text. Email has to be email.

 

Link to comment
Share on other sites

Remember, I'm talking in English.

 

The string up there doesn't mean anything. Just some random thing I typed by pounding random stuff on my keyboard. If you want to validate information, you have to tell me what kind of data is considered valid.

Link to comment
Share on other sites

Remember, I'm talking in English.

 

The string up there doesn't mean anything. Just some random thing I typed by pounding random stuff on my keyboard. If you want to validate information, you have to tell me what kind of data is considered valid.

 

 

Oh okay. Name should be strictly letters. Title and Company can contain letters and numbers. Email must be email as in have x@x.x

 

Telephone is optional but if possible should include only numbers. Message is optional and can be anything.

Link to comment
Share on other sites

This is customized just for that form.

 

function validateForm (frm) {
if (/[^a-z]/i.test(frm.Name.value)) window.alert("Name must contain only letters");
else if (/[^a-z\d]/i.test(frm.Title.value)) window.alert("Title must contain only letters and numbers");
else if (/[^a-z\d]/i.test(frm.Company.value)) window.alert("Company must contain only letters and numbers");
else if (!/^1?\-?(\d{3}\-?){3}$/.test(frm.Telephone.value)) window.alert("Telephone must contain digits and -");
else if (!/^[-.+_\da-z]+@[-.\da-z]+\.[a-z]{2,4}$/.test(frm.Email.value)) window.alert("Email is not in the correct format");
else return true;
return false;
}

 

In your form, replace the onsubmit attribute value with "javascript:return validateForm(this);"

Link to comment
Share on other sites

This is customized just for that form.

 

function validateForm (frm) {
if (/[^a-z]/i.test(frm.Name.value)) window.alert("Name must contain only letters");
else if (/[^a-z\d]/i.test(frm.Title.value)) window.alert("Title must contain only letters and numbers");
else if (/[^a-z\d]/i.test(frm.Company.value)) window.alert("Company must contain only letters and numbers");
else if (!/^1?\-?(\d{3}\-?){3}$/.test(frm.Telephone.value)) window.alert("Telephone must contain digits and -");
else if (!/^[-.+_\da-z]+@[-.\da-z]+\.[a-z]{2,4}$/.test(frm.Email.value)) window.alert("Email is not in the correct format");
else return true;
return false;
}

 

In your form, replace the onsubmit attribute value with "javascript:return validateForm(this);"

 

 

Thanks, the popup is working in firefox finally...but incorrectly.

 

Go to http://www.architecturalinstallationteam.com/index.php?p=contact_us where the new script has been implemented to see what I mean

Link to comment
Share on other sites

Does the script you wrote allow for either XXXXXXXXXX and XXX-XXX-XXXX or is it only XXX-XXX-XXXX on the telephone field?

 

Cause if it is one or the other, (idk since the script doesn't allow anything for telephone at the momment) then id prefer the no - format

Link to comment
Share on other sites

Define incorrectly. What's wrong with it?

 

Edit: Well check your own format. I did exactly as you specified.

 

either 1-xxx-xxx-xxx, xxx-xxx-xxx,  1xxxxxxxxx, or xxxxxxxxx should be allowed

 

 

Are you using firefox? if all of them work then its fine...except in firefox NONE of them work.

 

and it doesn't have a name is required, title is required, etc. at least in firefox when i leave blank and hit preview only telephone comes up. but then if i put a # in name THEN it shows up.

Link to comment
Share on other sites

Oops, forgot about the required part. Sorry, sorry.

 

function validateForm (frm) {
   if (frm.Name.value.length > 0 && /[^a-z]/i.test(frm.Name.value)) window.alert("Name must contain only letters");
   else if (frm.Title.value.length > 0 && /[^a-z\d]/i.test(frm.Title.value)) window.alert("Title must contain only letters and numbers");
   else if (frm.Company.value.length > 0 && /[^a-z\d]/i.test(frm.Company.value)) window.alert("Company must contain only letters and numbers");
   else if (!/^1?\-?(\d{3}\-?){3}$/.test(frm.Telephone.value)) window.alert("Telephone must contain digits and -");
   else if (frm.Email.value.length > 0 && !/^[-.+_\da-z]+@[-.\da-z]+\.[a-z]{2,4}$/.test(frm.Email.value)) window.alert("Email is not in the correct format");
   else return true;
   return false;
}

Link to comment
Share on other sites

Oops, forgot about the required part. Sorry, sorry.

 

function validateForm (frm) {
   if (frm.Name.value.length > 0 && /[^a-z]/i.test(frm.Name.value)) window.alert("Name must contain only letters");
   else if (frm.Title.value.length > 0 && /[^a-z\d]/i.test(frm.Title.value)) window.alert("Title must contain only letters and numbers");
   else if (frm.Company.value.length > 0 && /[^a-z\d]/i.test(frm.Company.value)) window.alert("Company must contain only letters and numbers");
   else if (!/^1?\-?(\d{3}\-?){3}$/.test(frm.Telephone.value)) window.alert("Telephone must contain digits and -");
   else if (frm.Email.value.length > 0 && !/^[-.+_\da-z]+@[-.\da-z]+\.[a-z]{2,4}$/.test(frm.Email.value)) window.alert("Email is not in the correct format");
   else return true;
   return false;
}

 

 

I am confused as to why the script is not working correctly in Firefox, IE, or Safari.

 

Attached are what I am talking about

 

[attachment deleted by admin]

Link to comment
Share on other sites

You're using the wrong format for telephone.

 

either 1-xxx-xxx-xxx, xxx-xxx-xxx,  1xxxxxxxxx, or xxxxxxxxx should be allowed

Match what you have in those screenshots to one of the format above. It doesn't match any. :-\

 

 

How does it not match xxxxxxxxxx? thats a standard phone number. the script should be able to handle any phone number. can we just change it so its not required but if they do input characters to make sure they are numbers? the format doesn't matter as much as the big picture of the script requiring only Name Title Company and Email which at the momment im not even sure it does correctly?

 

Thanks again for all the help,

Jeff

Link to comment
Share on other sites

*Ken2k7 sighs..

 

You really don't see it? It was your mistake to begin with. Check the format I quoted from you. And I mean look at it closely. Afterwards, if need be, I'll edit the JavaScript.

 

 

I see that there is one less x. but why would I want a odd phone number count?

 

Have you ever seen the form validation script provided at http://www.viala.hu/frdl/formcheck/formcheck.html

 

Anyways I tried to implement that script into my page as well (in an html version for ease sake). Unfortunately this script doesn't work in my page with the basically same coding as in their demo page. (except the onkeypress telephone field)

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>AIT - Contact Us</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="default3.css" rel="stylesheet" type="text/css" />
<link href="validator.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="images/favicon.ico" />

<script src="js/chkform.js" type="text/javascript" charset="utf-8"></script>
<script src="js/chkform_lang.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" language="javascript">
var method = 1;
</script>        
<script type="text/javascript" language="javascript">

function configureValidation(f,alerttype){
  f.Name.isAlphaNumeric = true;
  f.Title.isAlphaNumeric = true;
  f.Company.isAlphaNumeric = true;
  f.Telephone.isPhoneNumber = true;
  f.Email.isEmail = true;
  f.Message.optional = true;
  
  var preCheck = (!f.infohtml.checked && !f.infocss.checked && !f.infojs.checked) ? errormsg[0] : null;
  return validateForm(f, preCheck, 'required', alerttype);
}
</script>

</head>
<body>
<div id="wrapper">
<!-- start header -->
<div id="logo">
<img src="images/logo.jpg" alt="" width="880" height="165" /></div>
<div id="header">
<div id="menu">
	<ul>
	  <li><a href="index.html">Home</a></li>
	  <li><a href="our_team.html">Our Team</a></li>
	  <li><a href="qualifications.html">Qualifications</a></li>
	  <li><a href="major_projects.html">Major ProjectS</a></li>
	  <li class="last current_page_item"><a href="contact_us.html">Contact US</a></li>
  </ul>
</div>
</div>
<!-- end header -->
</div>
<!-- start page -->
<div id="page">
<!-- start content -->
<div id="content">
	<div class="post">
		<h1 class="title">Contact Us</h1>
		<div class="entry">
    	<p>Want AIT to contact you? Simply enter your information in the fields below and submit. AIT will contact you as soon as possible.</p>
            
<form action="#" method="post" onSubmit="return configureValidation(this,method)" onReset="confirm(errormsg[99])">
<table width="840" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td style="width: 90px;">Name<span class="required_star">*</span>:
    </td>
    <td style="width: 750px;"><input name="Name" class="checkit" type="text" id="Name" size="50" /><div id="errordiv_Name" class="errordiv"></div></td>
  </tr>
  <tr>
    <td>Title<span class="required_star">*</span>:</td>
    <td><input name="Title" class="checkit" type="text" id="Title" size="50" /><div id="errordiv_Title" class="errordiv"></div></td>
  </tr>
  <tr>
    <td>Company<span class="required_star">*</span>:</td>
    <td><input name="Company" class="checkit" type="text" id="Company" size="50" /><div id="errordiv_Company" class="errordiv"></div></td>
  </tr>
  <tr>
    <td>Telephone:</td>
    <td><input name="Telephone"  class="checkit" type="text" onKeyPress="javascript:checkNumber(this);" onKeyUp="javascript:checkNumber(this);" size="50" /><div id="errordiv_Telephone" class="errordiv"></div></td>
  </tr>
  <tr>
    <td>Email<span class="required_star">*</span>:</td>
    <td><input name="Email" class="checkit" type="text" id="Email" size="50" /><div id="errordiv_Email" class="errordiv"></div></td>
  </tr>
  <tr>
    <td>Message:</td>
    <td><textarea name="Message" cols="120" rows="8"></textarea></td>
  </tr>
  <tr>
    <td> </td>
    <td>Fields marked with <span class="required_star">*</span> are required_star. <div class="submit" style="text-align: right;"><br />
      <input type="submit" onClick="javascript: method = 1;" name="submit" value="Method 1" class="button"> 
      <input type="submit" onClick="javascript: method = 2;" name="submit" value="Method 2" class="button"> 
      <input type="submit" onClick="javascript: method = 3;" name="submit" value="Method 3" class="button"> 
      <input type="submit" onClick="javascript: method = 4;" name="submit" value="Method 4" class="button"> 
      <input type="submit" onClick="javascript: method = 5;" name="submit" value="Method 5" class="button"> 
      <input type="reset" name="reset" value="Reset" class="button">
    </div></td>
  </tr>
</table>
</form>

	  </div>
  </div>
	</div>
<!-- end content -->
<div style="clear: both;"> </div>
</div>
<!-- end page -->
<!-- start footer -->
<div id="footer">
<p id="legal">Copyright © 2009 Architectural Installation Team • All right reserved • <a href="http://architecturalinstallationteam.com/legal.html" title="Legal Information" rel="gb_page_center[580, 235]">Legal</a> • <a href="http://validator.w3.org/check?uri=referer" title="Validate this website" onclick="window.open(this.href); return false;"><span style="font-size: 10px; font-weight: lighter;">&#8984;</span></a> • Designed by <span class="jmedia">JMedia</span></p>
</div>
<!-- end footer -->

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-356758-5");
pageTracker._trackPageview();
} catch(err) {}</script>

</body>
</html>

/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Viala :: http://www.viala.hu
Based on: Travis Beckham :: http://www.squidfingers.com | http://www.podlob.com
Based on: Manzi Olivier :: http://www.imanzi.com/ 
Based on: jgw (jgwang@csua.berkeley.edu )/ */

// |||||||||||||||||||||||||||||||||||||||||||||||||||||
//
// Coded by Viala
// http://www.viala
// If want to use this code, feel free to do so, but
// please leave this message intact.
//
// |||||||||||||||||||||||||||||||||||||||||||||||||||||
// --- version date: 23/10/2006-------------------------


function checkCapsLock( e ) {
var myKeyCode=0;
var myShiftKey=false;

// Internet Explorer 4+
if ( document.all ) {
	myKeyCode=e.keyCode;
	myShiftKey=e.shiftKey;

// Netscape 4
} else if ( document.layers ) {
	myKeyCode=e.which;
	myShiftKey=( myKeyCode == 16 ) ? true : false;

// Netscape 6
} else if ( document.getElementById ) {
	myKeyCode=e.which;
	myShiftKey=( myKeyCode == 16 ) ? true : false;

}

// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) {
	alert( errormsg[100] );

// Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
} else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) {
	alert( errormsg[100] );

}
}

function CalcKeyCode(aChar) {
  var character = aChar.substring(0,1);
  var code = aChar.charCodeAt(0);
  return code;
}

function checkNumber(val) {
  var strPass = val.value;
  var strLength = strPass.length;
  var lchar = val.value.charAt((strLength) - 1);
  var cCode = CalcKeyCode(lchar);


  /* Check if the keyed in character is a number
     do you want alphabetic UPPERCASE only ?
     or lower case only just check their respective
     codes and replace the 48 and 57 */

  if (cCode < 48 || cCode > 57 ) {
    var myNumber = val.value.substring(0, (strLength) - 1);
    val.value = myNumber;
  }
  return false;
}
function isEmpty(str){
  return (str == null) || (str.length == 0);
}
// returns true if the string is a valid email
function isEmail(str){
  if(isEmpty(str)) return false;
  var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
  return re.test(str);
}

// returns true if the string only contains characters 0-9
function isNumeric(str){
  var re = /[\D]/g
  if (re.test(str)) return false;
  return true;
}
// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str){
  var re = /[^a-zA-Z0-9]/g
  if (re.test(str)) return false;
  return true;
}
// returns true if the string's length equals "len"
function isLength(str, len){
  return str.length == len;
}
// returns true if the string's length is between "min" and "max"
function isLengthBetween(str, min, max){
  return (str.length >= min)&&(str.length <= max);
}
// returns true if the string is a US phone number formatted as...
// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
function isPhoneNumber(str){
  //var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
  var re = /^\+\d{2,3}\ \(\d{2,3}\)\ \d{6,7}$/
  return re.test(str);
}
// returns true if the string is a valid date formatted as...
// mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy
function isDate(str){
  //var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/
  var re = /^(\d{4})[-\s\.\/](\d{1,2})[-\s\.\/](\d{1,2})$/
  if (!re.test(str)) return false;
  var result = str.match(re);
  var y = parseInt(result[1]);
  var m = parseInt(result[2]);
  var d = parseInt(result[3]);
  if(m < 1 || m > 12 || y < 1900 || y > 2100) return false;
  if(m == 2){
          var days = ((y % 4) == 0) ? 29 : 28;
  }else if(m == 4 || m == 6 || m == 9 || m == 11){
          var days = 30;
  }else{
          var days = 31;
  }
  return (d >= 1 && d <= days);
}
// returns true if "str1" is the same as the "str2"
function isMatch(str1, str2){
  return str1 == str2;
}
// returns true if the string contains only whitespace
// cannot check a password type input for whitespace
function isWhitespace(str){ // NOT USED IN FORM VALIDATION
  var re = /[\S]/g
  if (re.test(str)) return false;
  return true;
}
// removes any whitespace from the string and returns the result
// the value of "replacement" will be used to replace the whitespace (optional)
function stripWhitespace(str, replacement){// NOT USED IN FORM VALIDATION
  if (replacement == null) replacement = '';
  var result = str;
  var re = /\s/g
  if(str.search(re) != -1){
    result = str.replace(re, replacement);
  }
  return result;
}
// validate the form
function validateForm(f, preCheck, newClass, alerttype){
  var errors = '';
  var errorsa = '';
  var errordivs = '';
  if(preCheck != null) errors += preCheck;
  var i,e,t,n,v;
  for(i=0; i < f.elements.length; i++){
    e = f.elements[i];
    
    if(e.optional) continue;
    t = e.type;
    n = e.id;
    v = e.value;
    if(t == 'text' || t == 'password' || t == 'textarea'){
      
      if(isEmpty(v)){
        errors += n+errormsg[1]+ '<br>';
        errorsa += n+errormsg[1]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[1];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      if(v == e.defaultValue){
        errors += n+errormsg[2]+ '<br>';
        errorsa += n+errormsg[2]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[2];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      if(e.isAlpha){
        if(!isAlpha(v)){
        errors += n+errormsg[3]+ '<br>';
        errorsa += n+errormsg[3]+'\n';
        overlib('eaaaa');
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[3];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      }                              
      if(e.isNumeric){
        if(!isNumeric(v)){
        errors += n+errormsg[4]+ '<br>';
        errorsa += n+errormsg[4]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[4];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      }
      if(e.isAlphaNumeric){
        if(!isAlphaNumeric(v)){
        errors += n+errormsg[5]+ '<br>';
        errorsa += n+errormsg[5]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[5];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      }
      if(e.isEmail){
        if(!isEmail(v)){
        errors += v+errormsg[6]+ '<br>';
        errorsa += n+errormsg[6]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[6];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      }
      if(e.isLength != null){
        var len = e.isLength;
        if(!isLength(v,len)){
        errors += n+errormsg[7]+ len + '<br>'; 
        errorsa += n+errormsg[7]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[7]+ len;
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      }
      if(e.isLengthBetween != null){
        var min = e.isLengthBetween[0];
        var max = e.isLengthBetween[1];
        if(!isLengthBetween(v,min,max)){
        errors += n+errormsg[8] + min + '-' + max + '<br>';
        errorsa += n+errormsg[8] + min + '-' + max + '\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[8] + min + '-' + max;
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      }
      if(e.isPhoneNumber){
        if(!isPhoneNumber(v)){
        errors += v+errormsg[9]+ '<br>';
        errorsa += n+errormsg[9]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[9];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      }
      if(e.isDate){
        if(!isDate(v)){
        errors += v+errormsg[10]+ '<br>'; 
        errorsa += n+errormsg[10]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[10];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      }
      if(e.isMatch != null){
        if(!isMatch(v, e.isMatch)){
        errors += n+errormsg[11]+ '<br>';
        errorsa += n+errormsg[11]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[11];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
      }
    }
    if(t.indexOf('select') != -1){
      if(isEmpty(e.options[e.selectedIndex].value)){
        errors += n+errormsg[12]+ '<br>';
        errorsa += n+errormsg[12]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[12];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
    }
    if(t == 'file'){
      if(isEmpty(v)){
        errors += n+errormsg[13]+'<br>';
        errorsa += n+errormsg[13]+'\n';
        e.className=newClass;
        errordivs = 'errordiv_' + e.name;
        if ((alerttype == '4' || alerttype == '5') && document.getElementById(errordivs)) {
        document.getElementById(errordivs).innerHTML = n+errormsg[13];
        document.getElementById(errordivs).style.display = 'block';
        
    }
        continue;
      }
      else {
        e.className='checkit';
      }
    }
  }
  div = document.getElementById('errordiv');
  if(errors != '') {
  if(alerttype == '2' || alerttype == '3' || alerttype == '5') {
      alert(errorsa);
      }    
  if(alerttype == '1' || alerttype == '3') {
      return dispErr(errors, div);
      }    
  }
  div.style.display="none";
  return errors == '';
}

dispErr = function(error, divo) {
  divo.style.display="block";
  divo.innerHTML = error;
  return false;
}


/*
The following elements are not validated...

button   type="button"
checkbox type="checkbox"
hidden   type="hidden"
radio    type="radio"
reset    type="reset"
submit   type="submit"

All elements are assumed required and will only be validated for an
empty value or defaultValue unless specified by the following properties.

isEmail = true;          // valid email address
isAlpha = true;          // A-Z a-z characters only
isNumeric = true;        // 0-9 characters only
isAlphaNumeric = true;   // A-Z a-z 0-9 characters only
isLength = number;       // must be exact length
isLengthBetween = array; // [lowNumber, highNumber] must be between lowNumber and highNumber
isPhoneNumber = true;    // valid phone number. See "isPhoneNumber()" comments for the formatting rules
isDate = true;           // valid date. See "isDate()" comments for the formatting rules
isMatch = string;        // must match string
optional = true;         // element will not be validated

alerttype = 0            // no error msg
alerttype = 1            // error msg in div
alerttype = 2            // error msg in alert
alerttype = 3            // error msg in div and alert
alerttype = 4            // error msg in separated div
alerttype = 5            // error msg in separated div and alert
*/

 

I was wondering if you could help me see what is wrong with this code in my page if it is getting boring for you to rewrite the other script.

 

I sat up for hours trying to figure it out...

 

Thanks again

 

Link to comment
Share on other sites

Well it's no so much as being an odd number, but I know some countries that have phone numbers of that format. I had a job once where I had to input business card info into Excel and there were a lot of odd numbers from countries like Germany or something like that. I can't remember.

 

I rather not look through all that if I don't have to. Just because it's so long. It would be easier for me to just rewrite it. Also, you should know that copying and pasting work from other people and asking for help here makes the help that much harder. It'll be better if you wrote something completely wrong.

function validateForm (frm) {
   if (/[^a-z]/i.test(frm.Name.value)) window.alert("Name must contain only letters");
   else if (/[^a-z\d]/i.test(frm.Title.value)) window.alert("Title must contain only letters and numbers");
   else if (/[^a-z\d]/i.test(frm.Company.value)) window.alert("Company must contain only letters and numbers");
   else if (!/^1?\-?(\d{3}\-?){2}\d{4}$/.test(frm.Telephone.value)) window.alert("Telephone must contain digits and -");
   else if (!/^[-.+_\da-z]+@[-.\da-z]+\.[a-z]{2,4}$/.test(frm.Email.value)) window.alert("Email is not in the correct format");
   else return true;
   return false;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.