'How to validate the Display Name and Email Address together in a string using JavaScript or jQuery?

How to validate a Display Name and Email Address in the following format?

"John Doe" [email protected]

After doing the necessary research, the closest SO question I can relate my requirements to is: Extract email and name with regex

However, I couldn't find something solid, online. I am posting this question here in case someone has already developed a solution that they can share with everyone.

Wishful thinking is that if it can behave like MailAddress Class from System.Net.Mail namespace. https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.mailaddress

function ValidateEmailAndDisplayName(emailAddressWithDisplayName) {
    // A solid logic that addresses following test cases.
}

Quouted Display Name: ","

emailAddressWithDisplayName = "John Doe" <[email protected]> //=> True

Display Name without double qoutes:

emailAddressWithDisplayName = John Doe <[email protected]> //=> True

Comma in Quouted Display Name: ","

emailAddressWithDisplayName = "Doe, John" <[email protected]> //=> True

Comma in Display Name without double qoutes: ,

emailAddressWithDisplayName = Doe, John <[email protected]> //=> True

Backslash before adding double qoute: \

emailAddressWithDisplayName = "John \"Middle Name\" Doe" <[email protected]> //=> True

Missing backslash before adding double qoute: \

ValidateEmailAndDisplayName('"John "Middle Name" Doe" <[email protected]>'); //=> False

Missing closing angular bracket: >

emailAddressWithDisplayName = "John Doe" <[email protected] //=> Flase

TIA



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source