使用PHP、JS和Ajax验证联系人表单
Validating contactform using PHP, JS and Ajax
我在验证输入到联系表格中的内容时遇到问题。
这是表格:
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function(){
$('#contact_messenbrinkeu').ajaxForm(
function(){
alert("Your message has been send!");
}
)
})
</script>
</head>
<body>
<section id="page">
<?php include("includes/header.php"); ?>
<section id="articles">
<article id="article1">
<div id="contact-form">
<form id="contact_messenbrinkeu" action="sendform.php" method="post">
<fieldset id="form">
<label for="name">Name*</label><br>
<input type="text" name="name" placeholder="Your Name"title="enter your name" class="alpha required"><br>
<label for="email">E-mail*</label><br>
<input type="email" name="email" placeholder="mail@example.com" title="Enter your e-mail address" class="mail required"><br>
<label for="phone">Phone</label><br>
<input type="text" name="phone" placeholder="00 45 12 34 56 78" class="numeric"><br>
<label for="website">Website</label><br>
<input type="text" name="website" placeholder="www.example.com" id="website"><br>
<label for="message">Message*</label><br id="message">
<textarea name="message" class="required"></textarea>
</fieldset>
<fieldset id="button">
<button type="submit">>> Send</button>
<button type="reset">reset <<</button>
</fieldset>
</form>
</div><!-- /end #contact-form -->
</article><!-- Article 1 end -->
</section>
<?php include("includes/jquery.php");?>
<script type="text/javascript">
/*<![CDATA[*/
jQuery.noConflict();
jQuery(document).ready(function($){
// when submit button is pressed
$("#contact_messenbrinkeu").submit(function() {
var pass = true;
var errors = {
required : 'this field is required',
email : 'enter a valid email address',
numeric : 'enter a number without spaces, dots or commas',
alpha : 'this field accepts only letters & spaces'
};
var tests = {
email : /^([A-Za-z0-9_'-'.])+'@([A-Za-z0-9_'-'.])+'.([A-Za-z]{2,4})$/,
numeric : /^[0-9]+$/,
alpha : /^[a-zA-Z ]+$/
};
// clear error messages
$(".error").removeClass();
$(".error-message").remove();
function displayError(el, type) {
$(el).parent().addClass("error").find('label').append('<span class='"error-message'"> – ' + errors[type] + '</span>');
}
$('.required, .email, .numeric, .alpha').each(function(){
var value = $(this).val();
var valueExists = value.length === 0 ? false : true;
var required = $(this).hasClass('required');
var email = $(this).hasClass('email');
var numeric = $(this).hasClass('numeric');
var alpha = $(this).hasClass('alpha');
if (required && value.length===0) {
displayError(this,'required');
pass=false;
}
else if (email && valueExists && !tests.email.test(value)) {
displayError(this,'email');
pass=false;
}
else if (numeric && valueExists && !tests.numeric.test(value)) {
displayError(this,'numeric');
pass=false;
}
else if (alpha && valueExists && !tests.alpha.test(value)) {
displayError(this,'alpha');
pass=false;
}
});
return pass;
});
});
/*]]>*/
</script>
以及提交表单时调用的sendform.php:
<?php
ini_set("display_errors", "0");
$post_data = filter_input_array( INPUT_POST );
$name = $post_data["name"];
$email = $post_data["email"];
$phone = $post_data["phone"];
$website = $post_data["website"];
$message = $post_data["message"];
# select data that needs validation
$validate = array(
'required' => array($name,$email,$message),
'validEmail' => array($email),
'validNumber' => array($phone),
'validAlpha' => array($name)
);
$formcontent = "Name: $name 'nE-Mail: $email 'nPhone: $phone 'nWebsite: $website 'nMessage: $message 'n";
//*$formcontent = wordwrap($formcontent, 70, "'n", true);
$recipient = "mail@test.com";
$subject = "Testmail";
/*$mailheader = "From: $email 'r'n";**/
$mailheader .= "Reply-To: $name <$email>'r'n";
$mailheader .= "Return-Path: $name <$email>'r'n";
$mailheader .= "Content-Type: text/plain'r'n";
$mailheader .= "Organization: Sender Organization'r'n";
$mailheader .= "MIME-Version: 1.0'r'n";
$mailheader .= "Content-type: text/plain; charset=UTF-8'r'n";
$mailheader .= "X-Priority: 3'r'n";
$mailheader .= "X-Mailer: PHP". phpversion() ."'r'n";
$mailheader .= "From: $name <$email>'r'n";
function sendMail() {
global $formcontent, $recipient, $subject, $mailheader;
mail($recipient, $subject, $formcontent, $mailheader);
}
# error messages
$errorsMsgs = array(
'required' => 'Please fill out all required fields.',
'validEmail' => 'is an invalid email address.',
'validNumber' => 'is an invalid number.',
'validAlpha' => 'contains invalid characters. This field only accepts letters and spaces.'
);
$errorMarkup = "<h1>We found a few errors :-(</h1><h2>Please fix these errors and try again</h2><ol>";
$errorMarkupEnd = "</ol>";
$successMarkup = "<h1>Success!</h1><h2>Your form was sent successfully.</h2>";
$backMarkup = "<a href='"" . $_SERVER['HTTP_REFERER'] . "'">Back to form</a>";
# begin state
$valid = true;
# loop through fields of error types
foreach ($validate as $type => $fields) {
# loop through values of fields to be tested
foreach ($fields as $value) {
# throw error if value is required and not entered
if ($type === 'required' && strlen($value) === 0) {
$errorMarkup .= "<li>$errorsMsgs[$type]</li>";
$valid = false;
break;
}
else if (
$type === 'validEmail' && !filter_var($value, FILTER_VALIDATE_EMAIL) ||
$type === 'validNumber' && !preg_match('/^[0-9 ]+$/', $value) ||
$type === 'validAlpha' && !preg_match('/^[a-zA-Z ]+$/', $value)
) {
if (strlen($value) === 0) {break;} # skip check if value is not entered
$errorMarkup .= "<li>'"$value'" $errorsMsgs[$type]</li>";
$valid = false;
continue;
}
}
}
function isUTF8($string){
return (utf8_encode(utf8_decode($string)) == $string);
}
if ($valid) {
//*isUTF8($subject);
//*isUTF8($formcontent);
sendMail();
$body = $successMarkup . $backMarkup;
$title = "Form sent";
} else {
$body = $errorMarkup . $errorMarkupEnd . $backMarkup;
$title = "Form errors";
}
在这一点上,我正在努力解决两个问题:
如果在表单中输入无效字符,它不仅会为具有无效值的字段返回错误,还会为所有字符返回错误。
无论表单是否真的被发送,告诉你表单被成功发送的弹出窗口都会出现——所以我显然需要把它放在验证之后。
在contact.php表单中,您将首先获得与此类似的表单类型
<form action="post.php" name="contactUs" onsubmit="return validateForm();" method="post" >
这告诉你的联系人表单在哪里获取post.php表单,因为我的表单在同一个文件夹中,它只需要名称,你设置了表单的名称,对我来说是contactUs,这将在一分钟内解释,然后你必须提交,这是联系人表单底部的提交按钮,所以当有人点击提交时,它会返回validateForm(),也就是这个。
<script type="text/javascript">
function validateForm()
{
if (false == validate_required(
document.forms["contactUs"]["name"], "Name must be supplied"))
{
return false;
}
if (false == validate_email(
document.forms["contactUs"]["email"], "Valid email must be supplied"))
{
return false;
}
if (false == validate_product(
document.forms["contactUs"]["product"], "Please tell us your product type"))
{
return false;
}
if (false == validate_support(
document.forms["contactUs"]["support"], "Type of support must be supplied"))
{
return false;
}
if (false == validate_message(
document.forms["contactUs"]["message"], "A message must be supplied"))
{
return false;
}
return true;
}
function validate_required(field, alerttxt)
{
if (field.value == null || field.value == "")
{
alert(alerttxt);
return false;
}
else
{
return true;
}
}
function validate_email(field, alerttxt)
{
apos = field.value.indexOf("@");dotpos = field.value.lastIndexOf(".");
if (apos < 1 || dotpos - apos < 2) {
alert(alerttxt);
return false;
}
else
{
return true;
}
}
function validate_product(field, alerttxt)
{
if (field.value == null || field.value == "" || field.value == "What is Your Product?")
{
alert(alerttxt);
return false;
}
else
{
return true;
}
}
function validate_support(field, alerttxt)
{
if (field.value == null || field.value == "" || field.value == "Type of Support?")
{
alert(alerttxt);
return false;
}
else
{
return true;
}
}
function validate_message(field, alerttxt)
{
if (field.value == null || field.value == "" || field.value == "Please enter Message here:")
{
alert(alerttxt);
return false;
}
else
{
return true;
}
}
</script>
这是在你的表单下,这样它更容易找到脚本,我将以这个为例,希望能教会你理解需要知道的东西
if (false == validate_required(
document.forms["contactUs"]["email"], "Valid email must be supplied"))
{
return false;
这是它的功能
function validate_required(field, alerttxt)
{
if (field.value == null || field.value == "")
{
alert(alerttxt);
return false;
}
else
{
return true;
}
}
在你的if语句中,你键入了你的表单的名称,对我来说是contactUs,我的联系人表单的值的名称是name,所以这将检查名称是否有效。
在我的函数中,它检查它是否为null(空)或",如果它为空,则与空相同给他们alerttxt,它在我的validate_required中被定义为"必须提供有效的电子邮件",这是在函数validate_required(字段,alerttxt)中设置的,字段是我的表单的名称和我想要验证的字段的名称,alerttxt是上面显示的,如果它是空的,则返回false,如果不是,则返回true。
if语句是
if (false == validate_required)
您已经从表单和if false == validate_required
中得到了结果,如果validate_required
也是false,那么它们是相等的,而是给出警报消息,如果validate_required
是true,那么它们不匹配,语句也不是false,因此不需要验证,希望这有帮助,通读javascript,您将了解的含义
- 正在验证8个真/假复选框或复选框中的2个
- 在验证和发送邮件后更改联系人表单的 html
- jquery.validator和一个页面上的两个联系人表单将在提交时验证空表单
- 谷歌验证码(联系人仍然发送)
- 我正在验证一个联系人表单.我是不是过滤太多了
- 滚动至联系人表格7中的已验证字段(wordpress)
- 如何使用JS清理联系人表单后删除HTML5表单验证
- 验证HTML联系人表单
- 使用PHP、JS和Ajax验证联系人表单
- 如何使用JavaScript验证联系人表单
- 使用javascript验证联系人表单
- 使用jquery和php验证联系人表单
- PHP/JS联系人表单-验证
- 联系人字段的Javascript验证
- 联系人表单的Javascript验证
- 没有打开联系人页面的验证码
- Google联系人API错误:通过脚本加载请求超时.可能的原因:源URL不正确;提要需要身份验证
- 联系人表单默认值验证
- 在AngularJS中带服务器端验证的联系人表单
- Html5联系人表单- javascript和php验证的问题