我有一个在网络上免费提供的联系表。手指交叉它很棒,但是对于我有默认值(例如“全名”)的表单,我不确定如何让它在 JS 和 PHP 中验证这些字段。
这是我的 HTML:
<input type="text" name="contactname" id="contactname" class="required" role="input" aria-required="true" onfocus="if(this.value=='Full Name') this.value='';" onblur="if(this.value=='') this.value='Full Name';" value="Full Name" />
这是我的 JS:
$(document).ready(function(){
// validate signup form on keyup and submit
var validator = $("#contactform").validate({
rules: {
contactname: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
telephone: {
required: true,
minlength: 11
},
message: {
required: true,
minlength: 10
}
},
messages: {
contactname: {
required: "Please enter your Full Name",
minlength: jQuery.format("Your name needs to be at least {0} characters")
},
email: {
required: "Please enter a valid Email Address",
minlength: "Please enter a valid Email Address"
},
telephone: {
required: "Please enter a valid Telephone Number",
minlength: "Please enter a valid Telephone Number"
},
message: {
required: "You need to enter details!",
minlength: jQuery.format("Enter at least {0} characters")
}
},
// set this class to error-labels to indicate valid fields
success: function(label) {
label.addClass("checked");
}
});
});
<?php
//If the form is submitted
if(isset($_POST['contactform'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'email address'; //Put your own email address here
$subject = 'Contact Form';
$body = "Full Name: $name \nEmail Address: $email \nDetails: $comments";
$headers = 'From: Company <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
die(header('Location: index.html'));
}
}
?>
预先感谢您的帮助!