使用php验证联系表单中的名称 - $ error不正确?

时间:2016-08-19 13:39:39

标签: php validation email session

我在联系表单中验证名称时遇到了问题。如果名称字段留空,则表单应生成错误消息,例如"请输入您的姓名"。相反,没有错误消息,并且允许发送电子邮件。这是我的代码:

<form id="ajax-contact-form" class="form-horizontal" action="javascript:alert('success!');">
        <div class="row">
            <div class="span4">
                    <div class="control-group">
                        <label class="control-label" for="inputName">Your full name:</label>
                        <div class="controls">                    
                          <input class="span4" type="text" id="inputName" name="name" value="Your full name:" onBlur="if(this.value=='') this.value='Your full name:'"      onFocus="if(this.value =='Your full name:' ) this.value=''">
                        </div>
                    </div>              
                </div>  
        <div class="span4">
            <div class="control-group">
                <label class="control-label" for="inputEmail">Your email:</label>
                <div class="controls">                    
                  <input class="span4" type="text" id="inputEmail" name="email" value="Your email:" onBlur="if(this.value=='') this.value='Your email:'" onFocus="if(this.value =='Your         email:' ) this.value=''">
                </div>
            </div>
        </div>      
        <div class="span4">
            <div class="control-group">
                <label class="control-label" for="inputPhone">Phone number:</label>
                <div class="controls">                    
                  <input class="span4" type="text" id="inputPhone" name="phone" value="Phone number:" onBlur="if(this.value=='') this.value='Phone number:'"        onFocus="if(this.value =='Phone number:' ) this.value=''">
                </div>
            </div>
        </div>

        <div class="span4">
            <div class="control-group">
                <label class="control-label" for="inputDrums">Do you have a drum set?</label>
                <div class="controls">                    
                  <select input class="" type="text" id="inputDrums" name="drums">
                                <option>Do you have a drum set?</option>
                                <option>Yes</option>
                                <option>No</option>
                                </select>
                </div>
            </div>              
        </div>  

        <div class="span4">
            <div class="control-group">
                <label class="control-label" for="inputLevel">What level is the student?</label>
                <div class="controls">                    
                  <select input class="span4" type="text" id="inputLevel" name="level">
                                <option>What level is the student?</option>
                                <option>Beginner</option>
                                <option>Intermediate</option>
                                <option>Advanced</option>
                                </select>
                </div>
            </div>
        </div>

        <div class="span4">
            <div class="control-group">
                <label class="control-label" for="inputCity">What city do you live in?</label>
                <div class="controls">                    
                  <select input class="span4" type="text" id="inputCity" name="city">
                                <option>What city do you live in?</option>
                                <option>Boulder</option>
                                <option>Erie</option>
                                <option>Gunbarrel</option>
                                <option>Lafayette</option>
                                <option>Longmont</option>
                                <option>Louisville</option>
                                <option>Niwot</option>
                                <option>Other</option>
                                </select>
                </div>
            </div>
        </div>      

    </div>
    <div class="row">
        <div class="span12">
            <div class="control-group">
                <label class="control-label" for="inputMessage">Message:</label>
                <div class="controls">                                        
                  <textarea class="span12" id="inputMessage" name="content" onBlur="if(this.value=='') this.value='Message:'" 
                    onFocus="if(this.value =='Message:' ) this.value=''">Message:</textarea>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="span12">
            <div class="control-group captcha">
                <label class="control-label" for="inputCaptcha">Enter captcha numbers here:</label>
                <div class="controls">                    
                  <input class="" type="text" id="inputCaptcha" name="captcha" value="Enter captcha numbers here:" onBlur="if(this.value=='') this.value='Enter captcha numbers         here:'" onFocus="if(this.value =='Enter captcha numbers here:' ) this.value=''">
                  <img src="captcha/captcha.php">
        <img src="images/trans.png" style="width: 5px; height: 5px">          

    <INPUT TYPE="button" onClick="history.go(0)" VALUE="Refresh captcha" style="width: 120px; height: 42px">

                </div>
            </div>
        </div>
    </div>
    <button type="submit" class="submit">Send</button>
</form>

    **Contact.php**

    <?php
    /*
    Credits: Bit Repository
    URL: http://www.bitrepository.com/
    */

    include 'contact_config.php';
    session_start();
    error_reporting (E_ALL ^ E_NOTICE);

    $post = (!empty($_POST)) ? true : false;

    if($post)
    {
    include 'functions.php';

    $name = stripslashes($_POST['name']);
    $email = trim($_POST['email']);
    $phone = stripslashes($_POST['phone']);
    $drums = stripslashes($_POST['drums']);
    $level = stripslashes($_POST['level']);
    $city = stripslashes($_POST['city']);
    $subject = "Website Inquiry";
    $message = "

    Name: ".$_POST['name']
    ."

    E-mail Address: ".$_POST['email']
    ."

    Phone: ".$_POST['phone']
    ."

    Drums: ".$_POST['drums']
    ."

    Level: ".$_POST['level']
    ."

    City: ".$_POST['city']
    ."

    Message: ".$_POST['content'];


    $error = '';

    // Check name

    if(!$name)
    {
    $error .= 'Please enter your name.<br />';
    }
    // Check email

    if(!$email)
    {
    $error .= 'Please enter an e-mail address.<br />';
    }

    if($email && !ValidateEmail($email))
    {
    $error .= 'Please enter a valid e-mail address.<br />';
    }


    if(isset($_SESSION['captcha_keystring']) && strtolower($_SESSION['captcha_keystring']) != strtolower($_POST['captcha']))
    {
    $error .= "Incorrect captcha.<br />";
    }


    if(!$error)
    {

$mail = mail(WEBMASTER_EMAIL, $subject, $message,
       "From: ".$name." <".$email.">\r\n"
      ."Reply-To: ".$email."\r\n"
      ."X-Mailer: PHP/" . phpversion());

    if($mail)
    {
    echo 'OK';
    }

    }
    else
    {
    echo '<div class="notification_error">'.$error.'</div>';
    }

    }
    ?>

    **functions.php** 

        <?php
    function ValidateEmail($email)
    {

    $regex = '/([a-z0-9_.-]+)'. # name

    '@'. # at

    '([a-z0-9.-]+){2,255}'. # domain & possibly subdomains

    '.'. # period

    '([a-z]+){2,10}/i'; # domain extension 

    if($email == '') { 
return false;
    }
    else {
    $eregi = preg_replace($regex, '', $email);
    }

    return empty($eregi) ? true : false;
    }
    ?>   

4 个答案:

答案 0 :(得分:2)

您的Car可能实际上不是空的,可能是$_POST['name']。取代

' '

if(!$name){//...

您也可以修剪字符串。 e.g。

if(empty($name)){//...

答案 1 :(得分:0)

使用 isset 验证参数是否已发送

if(!isset($_POST['name']))
    {
        $error .= 'Please enter your name.<br />';
    }

尝试在条件之前打印$ error参数,看看输出是什么。

关于电子邮件变体,您可以在过滤器中使用PHP构建:

if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.";
}

Example #1 Validating email addresses with filter_var()

答案 2 :(得分:0)

在我的测试中,我发现空字符串总是评估为false,所以如果$_POST['name']变量是空字符串,你的代码应该可以工作。

然后,您可能会在没有意识到的情况下从表单中接收空格(例如空格或换行符)。在这种情况下,您可以像这样过滤$_POST变量:

$filtered = array_map("stripslashes", array_filter(array_map("trim", $_POST)));

完成此操作后,如果$filtered['name']为空或仅为空格,则不会设置$_POST['name']。可以使用issetarray_key_exists检查此内容。

答案 3 :(得分:0)

将值更改为占位符

原始代码

 <input class="span4" id="inputName" name="name" value="Your full name:" onblur="if(this.value=='') this.value='Your full name:'" onfocus="if(this.value =='Your full name:' ) this.value=''" type="text"> 


更改了代码

<input class="span4" id="inputName" name="name" placeholder="your full name" type="text"> 

占位符将出现在输入字段中。但是当您向字段添加内容时,占位符将消失。此外,当输入字段中的明文(使输入字段为空)并且您将焦点放在其上时,输入字段将保留其占位符值。

对所有输入字段执行此操作,例如电子邮件。

但是如果您仍想保留onfocus和onblur事件,请在提交时调用此函数(虽然我不推荐这样,因为只有在客户端启用了javascript时它才会起作用。)

 function()
 {
   var name = document.getElementById('inputName');
   if(name.value === "Your full name:" || name.value === "")
   {
       return false; 
   }
 }