PHP表单验证问题?

时间:2010-03-25 06:20:59

标签: php validation

我有一个验证电子邮件地址的表单,我希望能够将echo '<p class="error">Please enter a valid email address!</p>';放在网页的任何位置而无需将验证过程放在html中吗?

或者我应该在HTML表单中包含验证过程吗?

这是php代码。

if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) {
    $email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email']));
} else {
    echo '<p class="error">Please enter a valid email address!</p>';
}

1 个答案:

答案 0 :(得分:2)

略有不同

if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) { 
    $email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email'])); 
} else { 
    $error = 'Please enter a valid email address!'; 
} 

现在您可以在页面的任何位置打印$ error

好的,这样做:

if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) { 
    $email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email'])); 
    echo "valid ";
} else { 
    $error = 'Please enter a valid email address!'; 
    echo "invalid ";
} 
echo $error;
exit;

现在会说什么?

另一个例子:

<?php
$error="";
if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) { 
  $email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email'])); 
} else { 
  $error = 'Please enter a valid email address!'; 
  $email=htmlspecialchars($email);
} 
?>
<html>
<form>
<?php if ($error): ?>
  <p class="error"><?php echo $error?></p>
<?php endif ?>
Enter email: <input type="text" name="email" value="<?php echo $email?>">
<input type="submit">
</form>
</html>

现在有效吗?