Delphi: Regular Expression Email Confirmation

Since Delphi does not have a built-in regular expression library, have you seen a good function for checking email addresses that at least use Delphi RTL / VCL to some extent?

I don’t want to associate an additional * .dll with my regular expression support integration product, and I also need compatibility with Delphi 7. Embedding a regular expression library in exe increases its size, and I doubt that it’s worth adding the following 100 thousand. Because you need a 10-50 line email verification feature.

+5
source share
3 answers

The big problem with validating your email address is that RFC 822 is so wide that no regular expression will help.

Article I knew how to check my email address until I read the RFC . He quotes the RFC the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address( local partis the part before the sign @in the email address).

:
, , - SMTP- , .

, : SMTP- , SMTP-, , .

Indy SMTP ; , .

-

+5

Delphi, :

function TForm1.IsValidEmail(email: string): boolean;
const
  charslist = ['_', '-', '.', '0'..'9', 'A'..'Z', 'a'..'z'];
var
  Arobasc, lastpoint : boolean;
  i, n : integer;
  c : char;
begin
  n := Length(email);
  i := 1;
  Arobasc := false;
  lastpoint := false;
  result := true;
  while (i <= n) do begin
    c := email[i];
    if c = '@' then
    begin
      if Arobasc then  // Only 1 Arobasc
      begin
        result := false;
        exit;
      end;
      Arobasc := true;
    end
    else if (c = '.') and Arobasc then  // at least 1 . after arobasc
    begin
      lastpoint := true;
    end
    else if not(c in charslist) then  // valid chars
    begin
      result := false;
      exit;
    end;
    inc(i);
  end;
  if not(lastpoint) or (email[n] = '.')then  // not finish by . and have a . after arobasc
    result := false;
end;

For those who like to use RegExpression using a database server

function TForm1.IsValidEmail(const AMail: string): Boolean;
var
  lQry: TSQLQuery;
begin
  // no REGEXP in Delphi 2009 -> use of REGEPX Oracle
  lQry := TSQLQuery.Create();
  lQry.SQLConnection := SQLConnection1;
  try
    vQry.SQL.Text := 'SELECT REGEXP_SUBSTR( ' + QuotedStr(aMail) + ', ''^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,}$'' ) "EMAIL" FROM DUAL';  // ORACLE
    // vQry.SQL.Text := 'SELECT ' + QuotedStr(aMail) + ' REGEXP ''^[a-zA-Z0-9][a-zA-Z0-9.-]*[a-zA-Z0-9.-]@[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]\.[a-zA-Z]{2,4}$'';  // MySQL
    lQry.Open;
    Result := not lQry.Eof and ( lQry.FieldByName( 'EMAIL' ).AsString = AMail );
  finally
    FreeAndNil(lQry);
  end;
end;
-1
source

All Articles