简体   繁体   English

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

[英]Validating number and email fields before form is sent

I am new to PHP so sorry if my question seems a bit noobish. 我是PHP的新手,很抱歉,如果我的问题看起来有点愚蠢。 I am creating a contact form which is working great but I need to validate two fields; 我正在创建一个工作良好的联系表单,但我需要验证两个字段; the phone number and the email address, I need it to check that the phone number field has only numbers and is 11 digits long. 电话号码和电子邮件地址,我需要它来检查电话号码字段只有数字,长度是11位数。 The email field needs to be "something"@"something"."something". 电子邮件字段需要是“某事”@“某事”。“某事”。

If possible I would prefer to do it using only html or php (whichever is easiest), I guess that if there is a way to put the validation into the field properties, that would be the easiest way? 如果可能的话我宁愿只使用html或php(最简单的那个),我想如果有办法将验证放入字段属性,那将是最简单的方法吗? eg: in here: 例如:在这里:

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

If that is not possible then maybe in my PHP file which looks like so: 如果那是不可能的,那么可能在我的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 \r\n";
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>

Thank you in advance. 先感谢您。

There are two ways to check form data before submission, ie client-side: using JavaScript, and using new (HTML5) HTML attributes for the input element . 提交之前有两种方法可以检查表单数据,即客户端:使用JavaScript,以及为input元素使用新的(HTML5)HTML属性。 They can be used together if desired. 如果需要,它们可以一起使用。 Neither of them guarantees valid data; 它们都不能保证有效数据; client-side checking should be regarded as convenience to the user, not as a way of ensuring data validity (which you need to check server-side, in this case in PHP code). 客户端检查应被视为对用户的方便,而不是确保数据有效性的方法(您需要检查服务器端,在本例中是PHP代码)。

The HTML way can be exemplified this way: 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">

Using type="email" means that conforming browsers will check the email address format. 使用type="email"表示符合标准的浏览器将检查电子邮件地址格式。 This is a nontrivial task. 这是一项非常重要的任务。 Using type="tel" does not impose format restrictions (and the format varies by country and authority), but it may make browsers use a better user interface (such as a numeric keypad in touchscreen devices). 使用type="tel" 不会强加格式的限制(和格式由国家和权威而异),但它可能使浏览器使用了更好的用户界面(如触摸屏设备数字小键盘)。 The restriction is imposed by the pattern attribute. 限制由pattern属性强加。 The value \\d{11} means exactly 11 digits. \\d{11}表示正好是11位数。 (This is bad usability. I think you should allow spaces, and possibly parentheses and other characters as well, and strip them on the server. It is just too difficult to input an 11-digit number without any grouping. And 11 digits sounds arbitrary.) (这是糟糕的可用性。我认为你应该允许空格,也可能是括号和其他字符,并将它们剥离在服务器上。输入一个没有任何分组的11位数字太难了.11个数字听起来是任意的。)

There are several approaches to implementing the same in JavaScript. 有几种方法可以在JavaScript中实现相同的功能。 The pattern check is simple, whereas email format checks are very tough, and there are different library routines for it. 模式检查很简单,而电子邮件格式检查非常困难,并且有不同的库例程。 In general, the check should be fairly permissive, basically just checking that there is an “@” character. 一般来说,检查应该是相当宽松的,基本上只是检查是否有“@”字符。

If you want to validate this form before it is submitted, that will have to be done with javascript. 如果您想提交之前验证此表单,则必须使用javascript完成此表单。 However, you should still check in your server side code, as javascript could be disabled, which would render javascript validation useless. 但是,您仍应检查服务器端代码,因为可能会禁用javascript,这会导致javascript验证无效。

I've used this in the past, worked well for my needs. 我过去曾经用过这个,很适合我的需求。 http://validval.frebsite.nl/ http://validval.frebsite.nl/

Try adding three variables. 尝试添加三个变量。 First add a $pattern variable, then add two variables and use the switch function. 首先添加$pattern变量,然后添加两个变量并使用switch函数。

Sort of like... 有点像......

<?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;

This shows you what you want. 这会告诉你你想要什么。 Now try to validate it like... 现在尝试验证它...

  }

    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 />";
}
?>

As you can see, this will validate your form. 如您所见,这将验证您的表单。 You may have to configure it so the $pattern is set ti what you want it to be. 您可能需要对其进行配置,以便将$pattern设置为您想要的值。 This may not be the best way to do so, and I reccomend Javascript, but this is how you could do it with PHP and HTML. 这可能不是最好的方法,我推荐使用Javascript,但这是你用PHP和HTML做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM