2013-08-01 74 views
-1

我再次向您寻求精明的开发人员的帮助。 这是我为我的网站开发的联系方式:联系表格php验证

<div id="contactForm"> 
    <h2>Escr&iacute;banos</h2> 
    <div class="sepContainer"></div> 
    <form action="process.php" method="post" id="contact_form"> 
    <div class="name"> 
     <label for="name">Su nombre:</label> 
     <p> Por favor ingrese su nombre</p> 
     <input id=name name=name type=text required /> 
    </div> 
    <div class="empresa"> 
     <label for="empresa">Su empresa:</label> 
     <p> Por favor ingrese el nombre de la empresa a la cual pertenece (opcional):</p> 
     <input id=empresa name=empresa type=email required /> 
    </div> 
    <div class="telefono"> 
     <label for="telefono">Su tel&eacute;fono:</label> 
     <p> Por favor ingrese su n&uacute;mero de tel&eacute;fono (opcional):</p> 
     <input id=telefono name=telefono /> 
    </div> 
    <div class="email"> 
     <label for="email">Su E-Mail:</label> 
     <p> Por favor ingrese su E-Mail</p> 
     <input id=email name=email type=email required /> 
    </div> 
    <div class="message"> 
     <label for="message">Su mensaje:</label> 
     <p> Por favor ingrese su consulta</p> 
     <textarea id=message name=message rows=6 cols=10 required></textarea> 
    </div> 
    <div id="loader"> 
     <input name="submitted" type="submit" value="Enviar" /> 
    </div> 
    </form> 
</div> 

我想验证这种形式,所以我可以确保我能回到人们试图与我联系。

有没有人知道一个很好的代码来验证此表单? 我想确保在以下字段中输入:名称(仅文本,无特殊字符),telefono(可选字段;如果已填充:仅限电话号码,“ - ”允许),电子邮件(有效的电子邮件地址) ,消息(纯文本,不允许代码)。

如果有人能帮我解决这个问题,我会非常感激! 非常感谢!

+0

有谷歌上可以找到很多答案,[**点击这里**](HTTPS: //www.google.ca/search?q=mail+validation+php+form&ie=utf-8&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&channel=np&source=hp&gws_rd=cr)和你会看到有很多可用的选项。 –

+1

(附录)我认为'type = email'实际上是有效的HTML5标记。对于所有这些想知道,请参阅http://www.w3.org/TR/html-markup/input.email.html叫我“老派”哈哈老派“仍然有效”。 –

+0

我抬头看着谷歌,并尝试了几个代码,但似乎没有工作弗雷德!这是HTML5 – Locha91

回答

2

我同意弗雷德。不过,我想我会帮忙的。将表单发送到其他页面时存在一些问题。

如果您的表单在使用Javascript进行验证之后才会提交给process.php,那么您可以提供一个简单的完成消息,这样可以。但是,如果你想在process.php上验证它,那么用户将不得不返回带有表单的页面,并丢失一些数据。

一个更好的方法是(如果你想通过PHP验证)是离开的行动领域的空白<form action=""

然后使用下面的代码片段,以验证表单

<?php 
if(isset($_POST['name'])){ 
    $required_fields = array('name', 'email', 'telefono'); 
    $error = ''; 
    foreach($_POST as $k=>$v){ 
     $$k = $v; 
     if(in_array($k, $required_fields)){ 
      $error .= "$k is required<br />"; 
     } 
    } 

    if(!$error){ 
     //do whatever you want with the results here 
    } 
    else{ 
     echo $error; //print error 
    } 
} 
?> 

而且,你可能需要为名称字段的值和每个其他字段添加<?= $name; ?><?php echo $name; ?>。如果你已经汇报了PHP,然后初始化变量,所有的错误首先在因此页面的顶部:

$name = ''; $email = ''; //and so on 
+1

给你一个+1有两个理由,1)**感谢提及,** 2)**很好的解释和一个很好的例子。然而,我会说你可能不得不预先定义你的变量,例如'$ email = $ _ POST ['email'];'等,除非你已经在'foreach中处理过它($ _ POST为$ k => $ v){'?我对表格很满意,但我承认有些东西/方法我不知道;那么谁又是谁? (wink)干杯:) –

+0

@Fred谢谢:)是$$ k = $ v会自动将每个字段名称变成一个变量,所以''会创建一个变量'$ email'和'<输入名称=“地址”/>'会用输入字段的值创建一个变量'$ address'。我没有解释代码,因为我认为他会喜欢解决方案,并希望它可以帮助其他人,就像StackOverflow帮助我一样 – Onimusha

+0

不客气。好吧,我一定会研究你的代码,因为我确信它对所有人都有好处,包括我自己。如果有办法给你另一个+1,我会,欢呼!做得好:) –

0

我使用这个https://github.com/posabsolute/jQuery-Validation-Engine,如果你不介意使用jQuery,它会非常棒。

在字段验证之前,它不会提交表单。它验证大多数字段类型,包括电子邮件。你也可以使用这个插件通过ajax验证字段,例如检查用户名是否已经存在,以及没有提交表单的情况。

0

您可以使用Zend Validators来完成所有这些。

他们有一个简单的抽象验证器类,它有一个方法来检查输入是否通过验证器。您可以使用他们预先制作的验证器或通过扩展摘要来定义您自己的验证器。

不要像使用Pjack所建议的那样单独使用jQuery验证。精明的用户可以禁用JavaScript并提交未通过验证规则的数据。

0

沿着这些线路的东西,但也有图书馆,会做的方式更好。

即与jQuery等...

<?php 

session_start(); 
session_unset(); 


if(isset($_POST['name'])&&(!empty($_POST['name']))){ 
    //do stuff with name 

} else { 
$_SESSION['errors']['name'] = "Please enter a name"; 
} 

if(isset($_POST['email'])&&(!empty($_POST['email']))){ 

//do stuff with email 

} else { 
$_SESSION['errors']['email'] = "Please enter an email"; 
} 

//repeat for all other fields 


Then.... 

if(!empty($_SESSION['errors'])){ 
header("location: form.php"); //back to form 
} else { 
header("location: success.php"); 
} 

然后在你的HTML,保存为一个PHP文件,并添加错误.... 在一个跨度....

<div id="contactForm"> 
<h2>Escr&iacute;banos</h2> 
<div class="sepContainer"></div> 
<form action="process.php" method="post" id="contact_form"> 
    <div class="name"> 
    <label for="name">Su nombre:</label> 
    <p> Por favor ingrese su nombre</p> 

    <?php if(isset($_SESSION['errors']['name'])){echo "<span class='error'>".$_SESSION['errors']['name']."</span>";}?> 

    <input id=name name=name type=text required /> 
</div> 
<div class="empresa"> 
    <label for="empresa">Su empresa:</label> 
    <p> Por favor ingrese el nombre de la empresa a la cual pertenece (opcional):</p> 

    <?php if(isset($_SESSION['errors']['email'])){echo "<span class='error'>".$_SESSION['errors']['email']."</span>";}?> 

    <input id=empresa name=empresa type=email required /> 
</div> 

这种方式,您可以访问所有的错误$_SESSION['errors']阵列英寸

但上面的代码只会检查用户是否将东西输入框中。

它不会做任何奇特的事情,比如确保eemail实际上是一封电子邮件或任何东西。就像我说的......有些库处理这些东西要好得多。并且更精确。

但它的基本原理如上。

+0

好的,我不明白你的答案。首先你设置你的会话,然后你解除它。你可以解释吗? –

+0

我没有设置它...我开始它.....然后未设置,只是为了确保它再次填满之前,填充它。 (如果有错误),我想每次首先取消它,以便在没有错误时将其清空。 – KyleK

+0

我引用[** PHP手册**](http://php.net/manual/en/function。 session-unset.php)*“如果使用$ _SESSION(或PHP 4.0.6或更低版本的$ HTTP_SESSION_VARS),请使用unset()注销会话变量”*“。不是'session_unset();'如果/当注销某些内容或清除会话本身时使用?我的意思是,它会在录制会话后录制吗? –

0

另一种灵活的jQuery插件的浏览器端验证是“验证插件”在http://bassistance.de/

发现我会鼓励你总是箱服务器一侧,因为你不能依靠浏览器端验证的验证方法。用户可以随时控制浏览器中运行的JavaScript。

我总是开始编写服务器端验证并写入浏览器端,以便用户可以在此过程中获得一些反馈。

我经常做类似鬼武者财产以后进行简单的要求控制研究中写道:

<?php 


//Globals!! 
$required_fields = array('f1', 'f2', 'f3'); // to 'fn' 
///// "OR": 

//$field_tests = array('field_name' => 'validation_test'); 
$field_tests = array('field1' => 'required', 'field2' => 'tel', 'field3' => 'email', 'field4' => 'radio'); 

//For use when there are errors 
$restore_array = array(); 

//Depending on how you want to inform your users, this can be much more sofisticated.. 
//this method does not give you any way to indicate whitch field that did not validate correctly 
//$error_message = ''; 

$error_array = array(); 
$error_dictonary = array('field1' => 'explanation', 'field2' => 'other explanaiton'); 


function basic_server_side_validation(){ 
    global $error_array, $restore_array, $error_dictonary; 



    //REMEMBER TO DO APPROPRIATE trim() AND addslashes() WHERE APPLICABLE!! 
    //-- note: 
    //if you have checkboxes then implemented like <input type="checkbox" name="somename[]" /> 
    // Then this shoud be done recursively 
    foreach($_POST as $k => $v){ 
     $_POST[trim(addslashes($k))] = trim(addslashes($v)); 
    } 

    //You could do this only on errors... (you could alsow combine this whith the previous loop) 
    foreach($_POST as $k => $v){ 
     $restore_array[$k] = $v; 
    } 

    //if you just have required fields 
    //-- note: 
    //if you have checkboxes then implemented like <input type="checkbox" name="somename[]" /> 
    // Then this test need to check if that field is an array and so on (not shown here) 
    foreach($required_fields as $f){ 
     //if you use empty, note that empty("0") is true! (in some (most) cases thats what we want..) 
     if(!isset($_POST[$f]) || $_POST[$f] == '') // if(!isset($_POST[$f]) || emtpy($_POST[$f])) 
      $error_array[] = $f; 
    } 

    // "OR" : 

    foreach($field_tests as $field => $test){ 
     if(!isset($_POST[$f])){ 
      $error_array[] = $f; 
      continue; 
     } 

     if(! call_user_func('validate_'.$test, $_POST[$f])){ // or if(! 'validate_'.$test($_POST[$f])) 
      $error_array[] = $f; 
     } 

    } 


    if(!empty($error_array)){ 
     //Do somthing and show the form to the user agin 
     //The easiest way to do this is to hawe this code in a function and return at this time! 

     //NOT GLOBAL 
     //if $error_array and $restore_array and $error_dictonary IS NOT global 
     //return array('errors' => $error_array, 'restore' => $restore_array, 'mesages' => $error_dictonary); 

     //Whth globals: 
     return false; 
    } 

    ///Insert into DB?? (Here or in a nother function or in calling function when returning true) 
    return true; 


} 
//Define validation rules functions: 
function validate_required($field){ 
    if(isset($field)) 
     return true; 
    //default return false 
    return false; 
} 

function validate_telephone($field){ 
    //some code 
} 



if(isset($_POST['submit_button_name'])){ 
    if(!basic_server_side_validation()){ 
     show_form(); 
     //if show_form returns then we opt out here.. 
     return; 
    } 
    $db_status = do_db_stuff(); 

    if($db_status === false){ 
     //some error handler 
    } 
    //and so on 

}else{ 
    show_form(); 
} 

?> 

在你的HTML表单那么你可以做财产以后像(更换行动=“#”到合适的位置或“”):

function show_from(){ 

    echo '<form action="#" method="post">'; 

    if(isset($error_array['field_name'])) 
     echo '<p>', $error_dictonary['field_name'], '</p>'; 

    echo ' 
     <label>Some text: 
      <input type="text" name="field_name" value="',(isset($restore_array['field_name']) ? $restore_array['field_name'] : ''),'" /> 
     </label>'; 


    echo '</form>'; 


} 

注意,有很多方法可以做到表单验证,如果你需要大量的测试,然后创建一个“定义”可能是一个很好的路要走。从文章 “的形式解析器采用了苏超ARRAY ITERATOR” 在phparch.com 2009年9月(http://www.phparch.com/magazine/2009-2/september/) 例子:

$definition = array(
    'first_name' => array(
     'validate' => 1, 
     'validation_type' => 'alphanumeric', 
     'reg_exp' => '', 
     'error_message' => 'Only use alphanumeric characters', 
     'sanitize' => 1, 
     'sanitize_type' => 'safe', 
    ), 
    'last_name' => array(
     'validate' => 1, 
     'validation_type' => 'alphanumeric', 
     'reg_exp' => '', 
     'error_message' => 'Only use alphanumeric characters', 
     'sanitize' => 1, 
     'sanitize_type' => 'safe', 
    ), 
); 
+0

**哇!这是你在这里发生的一些复杂的编码。我只是希望通过OP的经验来判断,将能够做出“正面或反面”**。让我们希望OP“祝你好运”(眨眼) –

+0

而只是为了记录,**请求**是拼写**“必需”**和** feields **是**“字段”**。我们必须保持良好的“语法”ALIVE。 (wink) –

+0

谢谢Fred!我很抱歉拼写错误。我没有使用拼写检查器,现在感到尴尬:-)我是挪威人,在日常工作中我不会写太多英语。我的同事们指出,我经常拼错“领域”,我会尽力在下一次做对,并且要去更新这篇文章:-P –