I'm thinking about using a contact form with a user input for phone or email (by single input).
I would like to know if it's possible to use HTML number / email input for this somehow? and, should I do this type of validation on the server-side?
The HTML form:
<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>
The code from 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.";
}
I would like to know if it's possible to use HTML5 validation somehow for both. if not, it will be nice if anyone can share a better way to achieve this result with some JS/Jquery/AJAX code before sending the form data to the PHP file...
<?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";
}
}
?>
Here is the temporary solution using only html & php to get phone number or email with a single HTML form input:
html (with a textual type):
<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;
}
?>
I guess there is a better way to achieve this goal with JS but since there was no answer I hope this code can be useful too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.