RegEx for SMTP URL. Possible to Simplify?

  email, javascript, regex, smtp, typescript

Most RegEx examples for urls out there also include the directories which I don’t need to match.

Given the following urls, can you kindly confirm that my Current RegEx is precise? Could it be simplified?

Explicit TLS – (iCloud)
smtp://smtp.mail.me.com:587

Implicit TLS – (Gmail)
smtps://smtp.gmail.com:465

interface UrlParts {
  url: string,
  protocol: string,
  domain: string,
  port: number
}

// 1. url check
function urlValidate(url : any): UrlParts | null {

  // Convert to string and lowercase PRIOR to regex match.
  url = url.toString().toLowerCase();

  // REGEX Pattern to validate url.
  const urlRegexPattern = /(smtps?)://([d.a-z-]+.[a-z]{2,63}):(d{1,5})/;

  const match = url?.match(urlRegexPattern)

  // Perform match
  if(match) {
    return {
      url: match[0],
      protocol: match[1],
      domain: match[2],
      port: parseInt(match[3])
    }
  } else {
    return null;
  }

}

Usage:

urlValidate('smtp://smtp.mail.me.com:587');

{
  url: "smtp://smtp.mail.me.com:587",
  protocol: "smtp",
  domain: "smtp.mail.me.com",
  port: 587
}

urlValidate('smtps://smtp.gmail.com:465');

{
  url: "smtps://smtp.gmail.com:465",
  protocol: "smtps",
  domain: "smtp.gmail.com:465",
  port: 465
}

Source: Ask Javascript Questions

LEAVE A COMMENT