Solution 1
Well, you can indeed use a textarea
, split the posted value into an array, trim the lines, validate that each line contains a valid E-Mail address and do whatever you would like with the mails:
<form method="POST">
<p>
<label for="emails">
One E-Mail per line:
</label>
<textarea name="emails" id="emails" cols="80" rows="10">jdsjdhs@sdhjsdhj.de
jsddhs@ssdddhjsdhj.email
jsddhs@sdsddhj.tk
jdsjdsdhs@sdhjsdhj.org
jdsjdsdhs@sdhjsdhj.jetzt</textarea>
</p>
<p>
<input type="submit" value="Validate">
</p>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$emails = explode("\n", $_POST['emails']);
$emails = array_map('trim', $emails);
$emails = array_filter($emails, function ($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
});
$validEmailCount = count($emails);
echo <<<HTML
<p>
$validEmailCount valid E-Mails found.
</p>
HTML;
// Your database logic here
}
Solution 2
Based on the below comment thread, the OP is looking for an HTML only email "validation".
For that purpose, the input[type=email]
is probably the best choice.
To allow as many emails as wanted, I have written the below PHP, which adds a blank email field every time the form is submitted with the checkbox asking for another field is marked as on.
<?php
$emails = [''];
if (
$_SERVER['REQUEST_METHOD'] === 'POST' &&
isset($_POST['emails']) &&
is_array($_POST['emails'])
) {
$emails = $_POST['emails'];
if (
isset($_POST['add_mail']) &&
$_POST['add_mail'] === 'on'
) {
$emails[] = '';
} else {
print_r($emails);
die;
}
}
?>
<form method="POST">
<?php foreach ($emails as $email) : ?>
<p>
<input type="email" name="emails[]" value="<?= $email ?>">
</p>
<?php endforeach; ?>
<p>
<label for="add_mail">
Would like to enter one more E-Mail?
</label>
<input type="checkbox" name="add_mail" id="add_mail">
</p>
<p>
<input type="submit" value="Send">
</p>
</form>
Solution 3
Another solution would be to use a single input[type=text]
in combination with the [pattern]
attribute, and write a regular expression for it, that allows multiple email addresses.
<input type="text" pattern="…" required>
The emails could be separated by space, commas or semicolons, for example.
You would then do something like ,?
to allow a delimiter or not.