2011-03-12 125 views

回答

0

你必须为此使用ajax。或者,您可以验证它何时提交,使用JavaScript。这里是an intro to ajax

0

HTML5模式,可能有一个javascript回退(我收集一些浏览器已经支持:invalid伪类,你可以添加一个真正的类,以便能够使用JavaScript或生成表单时设置无效状态)。

0

或者您可以使用旧学校验证。 在服务器端,检查字段并将错误1添加到数组中。 然后你重建html页面,并验证每个字段:如果它在数组中,则添加一个类“错误”。 没有ajax,没有javascript。

2

的基本思路是:

  • 如果表单已提交,请检查数据
  • 是否确定,然后将这些数据
  • 否则,重新显示形式

注意:第一,你做这一切的服务器端:

  • 的用户提交表单,
  • 的数据被发送到服务器
  • 所述服务器分析该数据
  • 和重新显示的形式,如果必要的话


下面是一个快速的一部分代码演示了基本思路:

<?php 

// By default, no error 
$errors = array(
    'field1' => false, 
); 

// And all field have empty values 
$values = array(
    'field1' => isset($_GET['field1']) ? $_GET['field1'] : "", 
); 


if (isset($_GET['submit'])) { 
    // The form has been submitted 
    // => Check if all data is here 

    if (!isset($_GET['field1']) || empty($_GET['field1'])) { 
     $errors['field1'] = true; 
    } 

} 


// If there is no error on any field, then : 
//  - save the data 
//  - redirect to a page that says "data saved" 
// Else, continue, and re-display the form 


?> 
<style type="text/css"> 
    .error { 
     border: 1px solid red; 
    } 
</style> 
<form action="temp.php" method="get"> 
    <input type="text" name="field1" <?php if ($errors['field1'] == true) {echo 'class="error"';}?> value="<?php echo htmlspecialchars($values['field1'], ENT_COMPAT, 'UTF-8'); ?>" /> 
    <input type="submit" name="submit" value="Go !" /> 
</form> 


有两点要注意:

  • 如果你的表格是为了创建/修改数据,你会使用POST代替GET(但GET是更容易测试)
  • 当然,你需要比这多一点的HTML:我只发布了一个骷髅;-)
  • 而且您还需要更多的PHP代码,以保存数据,重定向和所有内容。


当使用这种解决方案,您可以用JavaScript代码的提升它,做检查的第一层,避免在错误的情况下往返到服务器。

你仍然会保持验证服务器上:客户(JavaScript)的的验证是这里让你的网站对用户更友好,但JS是不是总是启用,形式可以是伪造 - 所以你总是需要验证服务器上的数据!

0

您需要使用javascritpt。例如,您有一个用于输入名称的文本框。

 
<form name="myform" action="abc.php" method="post" onsubmit="validate();"> 
<input type="text" name="txt1"><div id = "givepost" style="display:none" align="center">*</div> 
<input type="submit" name="submit"> 
</form> 
<script type="text/javascript"> 
function validate() 
{ 
if(document.myform.txt1.value='') 
{ 
document.myform.txt1.focus(); 
document.getElementById("givepost").style.display="block"; 
return false; 
} 
} 

它会显示*如果文本框是空的。你可以改变的方式来显示错误

2

这也可以帮助你:http://flowplayer.org/tools/demos/validator/index.html 或者,如果你想这样做在PHP中:(简单)

<?php 
if($_GET["name"] == "name"){ 
    $returnStyle1 = "background-color: green;"; 
}else{ 
    $returnStyle1 = "background-color: red;"; 
} 
if($_GET["password"] == "123"){ 
    $returnStyle2 = "background-color: green;"; 
}else{ 
    $returnStyle2 = "background-color: red;"; 
} 
?> 
<form method='get' action='<?php echo $_SERVER["SCRIPT_NAME"]; ?>'> 
    <input type='text' name='name' style='<?php echo $returnStyle1; ?>' value='Username (name)' /> 
    <input type='password' name='password' style='<?php echo $returnStyle2; ?>' value='password (123)' /> 
    <input type='submit' value='validate' />
</form>

尝试输入“姓名” &“123” - >验证