在发送表单之前验证号码和电子邮件字段



我是PHP的新手,如果我的问题看起来有点无聊,我很抱歉。我正在创建一个联系人表单,它工作得很好,但我需要验证两个字段;电话号码和电子邮件地址,我需要它来检查电话号码字段是否只有数字并且有11位数长。电子邮件字段必须是"something"@"somethings"。"什么"。

如果可能的话,我更喜欢只使用html或php(以最简单的为准),我想如果有一种方法可以将验证放入字段属性中,那将是最简单的方法吗?例如:在这里:

<input type="text" name="email" id="email" class="text" form="contact_form" required/>

如果这是不可能的,那么也许在我的PHP文件中,它看起来是这样的:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Submitting...</title>
</head>
<body>
<?php
$Name = $_POST ['full_name'];
$Email = $_POST['email'];
$Number = $_POST['phone_number'];
$Company = $_POST['company_name'];
$Message = $_POST['message'];
$formcontent="Name: $Name
n Email: $Email 
n Number: $Number
n Company: $Company
n Message: $Message";
$recipient = "info@vicarage-support.com";
$subject = "Contact";
$mailheader = "From: $Email rn";
ini_set("sendmail_from","info@vicarage-support.com");
mail($recipient, $subject, $formcontent, $mailheader) or die("Please try again.");
echo("Form Submitted.");
?>
<script type="text/JavaScript">
<!--
setTimeout("location.href = 'http://www.vicarage-support.com/contact_us.html';",3000);
-->
</script>
</body>
</html>

提前谢谢。

在提交之前,有两种方法可以检查表单数据,即客户端:使用JavaScript,并为input元素使用新的(HTML5)HTML属性。如果需要,它们可以一起使用。它们都不能保证有效的数据;客户端检查应该被视为对用户的便利,而不是确保数据有效性的一种方式(您需要在服务器端检查,在本例中是在PHP代码中)。

HTML方式可以这样举例:

<input type="email" name="email" id="email" class="text" form="contact_form" 
required>
<input type="tel" name="tel" id="tel" class="text" form="contact_form" 
required pattern="d{11}" label="11 digits">

使用type="email"意味着符合条件的浏览器将检查电子邮件地址格式。这是一项不平凡的任务。使用type="tel"不会施加格式限制(格式因国家和地区而异),但它可能会使浏览器使用更好的用户界面(如触摸屏设备中的数字键盘)。该限制是由pattern属性施加的。值d{11}恰好表示11位数字。(这是糟糕的可用性。我认为你应该允许空格,可能还有括号和其他字符,并在服务器上去掉它们。在没有任何分组的情况下输入11位数太难了。11位数听起来很随意。)

有几种方法可以在JavaScript中实现相同的功能。模式检查很简单,而电子邮件格式检查很难,而且有不同的库例程。通常,检查应该相当宽松,基本上只是检查是否有"@"字符。

如果您想在提交前验证此表单,则必须使用javascript。但是,您仍然应该签入服务器端代码,因为javascript可能会被禁用,这将使javascript验证变得毫无用处。

我以前用过这个,很好地满足了我的需求。http://validval.frebsite.nl/

尝试添加三个变量。首先添加一个$pattern变量,然后添加两个变量并使用switch函数。

有点像。。。

<?php

$what = what you are checking (phone, email, etc)
$data = the string you want to check
function isValid( $what, $data ) {
switch( $what ) {

case 'Number':
$pattern = "/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i";
break;
//Change to a valid pattern, or configure it the way you want.
case 'Email':
$pattern = "/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i";
break;
default:
return false;
break;

这会向你展示你想要什么。现在试着验证它,就像。。。

}
return preg_match($pattern, $data) ? true : false;
}
$errors = array();
if( isset($_POST['btn_submit']) ) {
if( !isValid( 'phone', $_POST['Number'] ) ) {
$errors[] = 'Please enter a valid phone number';        
}
if( !isValid( 'email', $_POST['Email'] ) ) {
$errors[] = 'Please enter a valid email address';       
}
}
if( !empty($errors) ) {
foreach( $errors as $e ) echo "$e <br />";
}
?>

正如你所看到的,这将验证你的表单。你可能需要对它进行配置,以便$pattern设置为你想要的样子。这可能不是最好的方法,我建议使用Javascript,但这就是你使用PHP和HTML的方法。

相关内容

最新更新