php - 菜鸟: display err_msg on page (pt. 2)

标签 php javascript jquery error-handling validation

我昨天发布了此邮件,如果您对此做出了回应,并再次看到此邮件感到沮丧,我深表歉意!但是该表格现在根本无法使用,并且希望能为解决该问题提供帮助。

我有一个将数据发送到数据库并需要验证的表单。昨天至少可以正确验证,但是今天我什至无法正确连接到我的操作页面。这是两个页面:

带表格的页面:

    <?php
    session_start();
    $form_field =   array(  
                                'First_Name'                =>  '',
                                'Last_Name'             =>  '',
                                'Business_Name'             =>  '',
                                'Phone_Number'              =>  '',
                                'Web_Address'               =>  '',
                                'Email_Address'             =>  '',
                                'How_selling_product'           =>  '',
                                'Where_did_you_hear_about_us'   =>  '',
                            );
    foreach($form_field as $key => $value){$profiledata[$key]='';}              

    if(!empty($_SESSION['profiledata'])){   
        $profiledata    =   $_SESSION['profiledata'];
    }

    ?>

    [js]
    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;

      errors    += addValidation("req","first_name","- First Name is required.");
      errors    += addValidation("req","last_name","- Last Name is required.");

      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'; }
      } 

      errors    += addValidation("req","security_code","- Security Code is required."); 

      if(!errors){
        errors += addValidation("valid_lastname","first_name","- Please enter valid First Name");
        errors += addValidation("valid_lastname","last_name","- Please enter valid Last Name");
        errors += addValidation("numhyphenbrace","phone number","- Please enter valid Phone Number");
        errors += addValidation("valid_url","web address","- Please Enter Valid Web Address");
        errors += addValidation("email","email address","- Please Enter Valid Email");

      }
      if (errors) alert('The following error(s) occurred:\n'+errors);
      document.MM_returnValue = (errors == '');
    }
    [/js]

    <h1>Some content</h1>
    <p>Some text</p>

    <form id="form1" name="form1" method="post" action="mailform" onsubmit="MM_validateForm('Name','','R','Business Name','','R','Email Address','','R','How selling product','','R','Where did you hear about us','','R');return document.MM_returnValue">
        <div style="color:#FF0000; text-align:center;"><?php if(!empty($_GET['err_msg'])){echo $_GET['err_msg'];} ?></div>
            <fieldset>
                        <legend>Contact form</legend>
                    <p class="first">
                        <label for="name">First Name</label>
                        <input type="text" name="First Name" id="first_name" size="30" value="<?=htmlentities($profiledata['First_Name'])?>" />
                    </p>
                            <p class="first">
                        <label for="name">Last Name</label>
                        <input type="text" name="Last Name" id="last_name" size="30" value="<?=htmlentities($profiledata['Last_Name'])?>" />
                    </p>                
                    <p>
                        <label for="name">Phone Number</label>
                        <input type="text" name="Phone Number" id="phone number" size="30" value="<?=$profiledata['Phone_Number']?>" />
                    </p>
                    <p>
                        <label for="email">Business Name</label>
                        <input type="text" name="Business Name" id="business name" size="30" value="<?=htmlentities($profiledata['Business_Name'])?>" />
                    </p>
                    <p>
                        <label for="email">Web Address</label>
                        <input type="text" name="Web Address" id="web address" size="30" value="<?=$profiledata['Web_Address']?>" />
                    </p>
                    <p>
                        <label for="email">Email</label>
                        <input type="text" name="Email Address" id="email address" size="30" value="<?=$profiledata['Email_Address']?>" />
                    </p>            
            </fieldset>
            <fieldset>                                                                          
                    <p>
                        <label for="message">Describe how you plan on selling this product</label>
                        <textarea name="How selling product" id="How selling product" cols="30" rows="4"><?=htmlentities($profiledata['How_selling_product'])?></textarea>
                    </p>    
                    <p>
                        <label for="message">Where did you hear about us?</label>
                        <textarea name="Where did you hear about us" id="Where did you hear about us" cols="30" rows="4"><?=htmlentities($profiledata['Where_did_you_hear_about_us'])?></textarea>
                    </p>
                            <p>
                                <img src="CaptchaSecurityImages.php?width=100&height=40&characters=5" /><br />
                        <label for="security_code">Security Code: </label><input id="security_code" name="security_code" type="text" />
                            </p>                
            </fieldset>
                <p class="submit"><button type="submit">Send</button></p>
                <input name="mailform_address" type="hidden" value="email@address.com" />
    </form>

Mailform.php成功:
<?php 
session_start(); 
include("connect.php");

function valid_email($str)
{
    return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}

function is_url($str)
{
    return ( ! preg_match("/^((www)\.)?((\w+|[\d]?+)+(\.|\-)(\w+[\d]?+))+(\w)$/", $str)) ? FALSE : TRUE;
}

function valid_phone($str)
{
    $Num = $str;
    $Num = ereg_replace("([     ]+)","",$Num);;
    $Num = eregi_replace("(\(|\)|\-|\+)","",$Num);
    if(!is_numeric($Num))
    {       
        return FALSE;
    }   
    else
        return TRUE;
}

$form_field =   array(  
                            'First_Name'                    =>  '',
                            'Last_Name'                     =>  '',
                            'Business_Name'                 =>  '',
                            'Phone_Number'                  =>  '',
                            'Web_Address'                   =>  '',
                            'Email_Address'                 =>  '',
                            'How_selling_product'           =>  '',
                            'Where_did_you_hear_about_us'   =>  '',
                        );
foreach($form_field as $key => $value){$profiledata[$key]=trim($_POST[$key]);}

$_SESSION['profiledata']    =   $profiledata;

$emailto = NULL;
$emailmessage = "Dealer Contact Form\n";
$emailsubject = "Dealer Contact Form";

if(!empty($_POST)){

    //echo "<pre>";print_r($_POST);die;

    if( $_SESSION['security_code'] != $_POST['security_code'] || empty($_SESSION['security_code'] ) ) {

        // Insert your code for showing an error message here
        $err_msg    = 'Sorry, you have provided an invalid security code';
        header("Location: reseller.php?err_msg=".urlencode($err_msg));
        return;

    } else {
        unset($_SESSION['security_code']);  
    }

    $fname      =   html_entity_decode(trim($_POST['First_Name']));
    $lname      =   html_entity_decode(trim($_POST['Last_Name']));
    $company    =   html_entity_decode(trim($_POST['Business_Name']));
    $phone      =   html_entity_decode(trim($_POST['Phone_Number']));
    $website    =   html_entity_decode(trim($_POST['Web_Address']));
    $email      =   html_entity_decode(trim($_POST['Email_Address']));
    $notes      =   "Lead Source: ".html_entity_decode(trim($_POST['Where_did_you_hear_about_us']))."\n";
    $notes      .=  "Selling Method: ".html_entity_decode(trim($_POST['How_selling_product']));

    if(!valid_phone($phone)){
        $err_msg    = 'Please enter valid Phone Number.';
        header("Location: reseller.php?err_msg=".urlencode($err_msg));
        return;
    }

    if(!is_url($website)){
        $err_msg    = 'Please enter valid Web Address.';
        header("Location: reseller.php?err_msg=".urlencode($err_msg));
        return;
    }

    if(!valid_email($email)){
        $err_msg    = 'Please enter valid Email.';
        header("Location: reseller.php?err_msg=".urlencode($err_msg));
        return;
    }

    if(!stristr($website,"http://") && !stristr($website,"https://") && $website){
        $website    =   "http://".$website;
    }

    $res    =   mysql_query("SELECT in_customer_id FROM tbl_customer WHERE st_company_name = '".addslashes($company)."'");
    if(mysql_num_rows($res)){   
        $err_msg    =   'Business Name already exists';
        header("Location: reseller.php?err_msg=".urlencode($err_msg));
        return;
    }

    $res    =   mysql_query("SELECT st_user_name,st_user_email_id FROM tbl_admin_user WHERE st_user_email_id='".addslashes($email)."' AND flg_is_delete=0");
    if(mysql_num_rows($res)){   
        $err_msg    =   'Email already exists';
        header("Location: reseller.php?err_msg=".urlencode($err_msg));
        return;
    }

    $sql_customer   =   "INSERT INTO tbl_customer (`st_company_name`, `in_customer_type`, `st_customer_account`, `in_customer_phone_number`, `flg_customer_account_type`, `flg_disable_ordering`,  `st_message`, `in_status`, `dt_added_date`, `st_web`, `st_notes`) VALUES ('".addslashes($company)."', '2', '".time()."', '".addslashes($phone)."', '0', '1', 'You are an Inquiry customer', '0', '".date("Y-m-d H:i:s")."', '".addslashes($website)."', '".addslashes($notes)."')";

    mysql_query($sql_customer);
    $cust_id        =   mysql_insert_id();

    if($cust_id){
        $sql_user       =   "INSERT INTO tbl_admin_user (`st_user_first_name`, `st_user_last_name`, `st_user_company_name`, `st_user_email_id`, `in_customer_id`) VALUES ('".addslashes($fname)."', '".addslashes($lname)."', '".addslashes($company)."', '".addslashes($email)."', '".$cust_id."')";
        mysql_query($sql_user);

        $msg    =   "";
        $sub    =   "Thank you for contacting us.";

        ob_start();
        include("mailformat.php");
        $msg =  ob_get_contents();
        ob_end_clean();

        $headers    =   ''; 
        //$headers = "MIME-Version: 1.0\r\n";               
        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
        $headers .= "From: " . $_POST['mailform_address'] . "\r\n";
        $headers .= "Reply-To: ". $_POST['mailform_address'] . "\r\n";
        $headers .= "Bcc: email@address.com";

        if (@mail($email, $sub, $msg, $headers))
        {
            session_unset('profiledata');
        }
    }

    foreach($_POST as $name => $value)
    {
        if ($name == 'mailform_address')
        {
            $emailto = $value;
        }
        elseif($name    !=  "security_code")
        {
            $emailmessage .= $name . ": " . $value . "\n";
        }
    }
    session_unset('profiledata');
}

?>

    <?            
        if (@mail($emailto, $emailsubject, $emailmessage))
        {
        ?>
<p>We'll be in touch within two business days.  If you haven't heard back from us within two business days, please <a href="contact">contact us</a></p>
    <?
        }
        else
        {
        ?>    
<p>E-mail could not be sent. Please <a href="contact">contact us</a>.</p>   
        <?
        }
        ?>

谢谢你的协助。

最佳答案

我承认我没有彻底阅读您的代码,但是以下任何一个都可能是您的问题:

  • 在调用脚本中的MM_validateForm()时,我认为您需要传递HTML表单字段的名称,但是尽管每个参数似乎都是正确的,但第一个是“名称”,它似乎不是有效的表单字段。
  • addValidation()中的MM_validateForm()函数是什么,它有什么作用?由于我看不到它的定义,因此我认为它可能在您的JS中产生错误。
  • MM_validateForm()中,在行号之后。 3&4,似乎变量errors永远不会为空,从而阻止您提交表单?

  • 我不清楚您停留在哪一点-您的表格根本没有提交吗?您是否尝试在errors的末尾发出MM_validateForm()变量的警报。也许有帮助。

    关于php - 菜鸟: display err_msg on page (pt. 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6550820/

    相关文章:

    php - 在提交上传表单之前获取所选文件的内容

    php - 使用非自动生成的 ID 链接两个实体

    javascript - 切换CSS样式表时遇到麻烦(移动到桌面)

    javascript - 使用 jQuery 删除相同的重复文本

    php - fatal error : Class 'TestCase' not found in laravel 5

    php - PHP 中带和不带 DST 的时区

    javascript - 在 jquery 中排序事件

    javascript - 仅在 promise 解析时使用值

    javascript - 如何根据给定的粒度和js中的另一个日期计算日期?

    Jquery 撤消对 DOM 的最后更改