我正考虑使用联系表单和电话或电子邮件的用户输入(通过单一输入)。
我想知道是否有可能以某种方式使用HTML编号/电子邮件输入?我应该在服务器端进行这种类型的验证吗?
HTML 表单:
<form name="contact" target="contact.php" method="post">
<input name="fullname" placeholder="Name" type="text" value="" minlength="2" required="">
<input name="emailPhone" placeholder="email / phone" type="email" value="" required="">
<input value="send" type="submit">
</form>
来自 contact.php 的代码:
$name = trim(stripslashes($_POST['fullname']));
$ep_input = trim(stripslashes($_POST['emailPhone']));
// Name validation
if (strlen($name) < 2) {
$error['name'] = "Invalid name";
}
// Email and phone number validation. first, the email...
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $ep_input)) {
$error['email'] = "invalid email address.";
}
// Now the phone (should be more accurate but we keep it simple for now...)
else if (!preg_match('/^[0-9]*$/', $ep_input) {
$error['phone'] = "invalid phone number.";
}
我想知道是否有可能以某种方式使用HTML5验证。如果没有,那么在将表单数据发送到PHP文件之前,如果有人能够使用一些JS / Jquery / AJAX代码分享更好的方法来实现这个结果,那将是很好的...
答案 0 :(得分:0)
<?php
$ep=trim(stripslashes($_POST['emailPhone']));
if(is_numeric($ep))
{
if(!preg_match('/^\d{10}$/',$ep))
{
echo "invalid phone";
}
}
else
{
if (!filter_var($ep, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
}
}
?>
答案 1 :(得分:0)
以下是仅使用html&amp; amp;的临时解决方案php使用单个HTML表单输入获取电话号码或电子邮件:
html (带文字类型):
<input name="emailPhone" placeholder="email / phone" type="text" value="" required="">
PHP :
<?php
$name = trim(stripslashes($_POST['fullname']));
$ep = trim(stripslashes($_POST['emailPhone']));
// Check phone number for 10 digits
if(is_numeric($ep))
{
if(!preg_match('/^\d{10}$/',$ep)) {
$error = "invalid phone number.";
}
$eptype = "phone";
}
// Check valid email format
else
{
if (!filter_var($ep, FILTER_VALIDATE_EMAIL)) {
$error = "invalid email address.";
}
$eptype = "email";
}
// Send the information via email with php or show the error
$mailto = "email@example.com";
$massage = "Please contact". $name ."via ". $eptype .": ". $ep;
if (!$error) {
$sendmail = mail($mailto, "Subject", $massage);
}
else {
echo $error;
}
?>
我想有一种更好的方法可以用JS实现这个目标,但由于没有答案,我希望这段代码也很有用。