0

Looking to create a form validation on email text field. Have previously used validation to ensure correct email is produced.

But here looking to create a more custom rule which allows only emails ending in the format .ac.uk

Here a user would be able to provide any university/college/instituion as long as the last 6 characters in the string = .ac.uk with the general format for the mail as follows: email@university.ac.uk

Solution preferably in PHP, currently looking at employing a rule using the end part in this statement:

^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$

Making this part *(\.[a-z]{2,3}) relate to the .ac.uk

many thanks, much appreciated Jeanclaude

falinsky
  • 7,229
  • 3
  • 32
  • 56
Jeanclaude
  • 189
  • 1
  • 4
  • 15

1 Answers1

1

I would first run the email through filter_var($email, FILTER_VALIDATE_EMAIL) rather than using a simple regex. It's not perfect (I've found a few edge cases that don't validate correctly) but it works well. Once you know it's a valid email address you can simply trust substr($email, -6) == '.ac.uk' and be done with it. Something like:

if (filter_var($email, FILTER_VALIDATE_EMAIL) 
    && strtolower(substr(trim($email), -6))) === '.ac.uk') {

    // Valid
}
Matt S
  • 14,976
  • 6
  • 57
  • 76
  • (FILTER_VALIDATE_EMAIL is internally also implemented as regex.) – mario Oct 06 '13 at 15:47
  • Oh that's interesting. I'm assuming then it's one of those extremely elaborate regex's. I still trust it over the average regex I often see used, like the one in this post. – Matt S Oct 06 '13 at 15:49
  • 1
    It's indeed: https://github.com/php/php-src/blob/master/ext/filter/logical_filters.c#L500 There are [more elaborate ones](http://stackoverflow.com/a/1917982/345031) of course, which fully covered rfc2822. But it's sufficient for most cases. – mario Oct 06 '13 at 15:55
  • Ok nice one, Thank you i will try this approach using substr($email, -6) == '.ac.uk' and see how it works. – Jeanclaude Oct 06 '13 at 16:23