JSFiddle - React, Tailwind, and code Playground

by Dimitar Christoff

JavaScript

(function() {
    // define string prototypes for later testing.
    var validEmailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  
    String.prototype.isEmail = function() {
        // returns true if a string is a valid email
        return this.match(validEmailRegex);
    };
    
    String.prototype.isUKEmail = function() {
        // returns true if a string contains .co.uk
        return this.toLowerCase().indexOf(".co.uk") === -1 ? false : true;
    }
        
    String.prototype.isValidUKEmail = function() {
        // returns true if a mail is valid and uk.
        return this.isEmail() && this.isUKEmail();
    }
})();
 
// example use

// data set
var data = [
    '"Abc\@def"@example.com',
    '"Fred Bloggs"@example.com',
    '"Joe\\Blow"@example.com',
    '"Abc@def"@example.com',
    'customer/department=shipping@example.com',
    '$A12345@example.com',
    'foo@copmpany.co.uk',
    '!def!xyz%abc@example.com',
    '_somename@example.com'
 ];


// analyze them all
var count = data.length, isUK;
while (count--) {
    if (!data[count].isEmail())
        document.write("INVALID: the email <strong>" + data[count] + "</strong> incorrectly reported as non-valid<br />");
    else {
        isUK = (data[count].isUKEmail()) ? 'UK' : 'foreign';
        document.write("OK: the email <strong>" + data[count] + "</strong> recognised correctly, " + isUK + "<br />");
    }
 };
 
// exmaple where it only checks for a valid uk email.
document.write("<br/><br/>");

count = data.length;
while (count--) {
    if (data[count].isValidUKEmail())
        document.write("UK email: <strong>" + data[count] + "</strong><br/>");
}