You'd use something like;
<input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
So if you wanted to only allow a domain and subdomain in theory you'd use;
<input type="email" name="email" pattern="[a-z0-9._%+-]+@[example]+\.[com]{2,}/@[subdomain]+\.[example].\[com]$">
I only want to allow email responses from example.com
and subdomain.example.com
OR only allow email responses ending in .co.uk
which is most ideal.
Any help would be appreciated.
UPDATE
Using;
pattern="[a-zA-Z0-9-]+@sub.example.co.uk"
means that the validation will work.
But using:
pattern="[a-zA-Z0-9-]+@sub.example.co.uk|+@example.co.uk"
means that the validation will work but also allows domains like @gmail.com
etc.
UPDATE
Here's the code for the form.
<form action="./login.php" method="post">
<input type="email" id="email" minlength="13" maxlength="29" pattern="[a-zA-Z0-9-]+@subdomain@example.co.uk|+@example.co.uk" style="text-transform: lowercase" placeholder="Enter your email address." name="email" required=""><br>
<input type="submit">
</form>
Ideally I'd be able to set a list of allowed domains and specific email addresses so only jon@example.co.uk
, igor@example.co.uk
and stephen@example.co.uk
could submit. Can you match the beginning of the email as an array or the entire thing in the format of $allowedaddresses
to save exploding the @
from the domain.
</div>
Since you're only trying to match the domain name, which is generally the only reliably sane part of an email address, you can get away with a simply matching the end of a string with a regular expression.
$allowed_domains = [
'.co.uk',
'bar.co.uk'
];
$forbidden_domains = [
'baz.bar.co.uk'
];
// make it a bit easier to manage the lists of allowed/forbidden domains
function domain_suffix_to_regex($suffix) {
return sprintf('/.*%s$/', preg_quote($suffix));
}
$allowed = array_map('domain_suffix_to_regex', $allowed_domains);
$forbidden = array_map('domain_suffix_to_regex', $forbidden_domains);
$emails = [
'example@foo.bar.co.uk',
'example@bar.co.uk',
'example@baz.bar.co.uk'
];
foreach($emails as $email) {
$permitted = false;
foreach($allowed as $expr) {
if( preg_match($expr, $email) ) {
$permitted = true;
echo "$email allowed by expr: $expr
";
break;
}
}
if( $permitted ) {
foreach($forbidden as $expr) {
if( preg_match($expr, $email) ) {
$permitted = false;
echo "$email forbidden by expr: $expr
";
break;
}
}
}
var_dump($permitted);
}
Output:
example@foo.bar.co.uk allowed by expr: /.*\.co\.uk$/
bool(true)
example@bar.co.uk allowed by expr: /.*\.co\.uk$/
bool(true)
example@baz.bar.co.uk allowed by expr: /.*\.co\.uk$/
example@baz.bar.co.uk forbidden by expr: /.*baz\.bar\.co\.uk$/
bool(false)