Friday, April 3, 2009

Validating Email ID

Sometimes we are in a situation where we need to validate an email id in our applications. Recently I had one such requirement in one of my project and found this piece of code that validates an email id (string) and returns a boolean value indicating whether the email id is a well formed email id.


function InvalidEmailFormat(const AEmailAddress: String): Boolean;
var
LIndex: Integer;
LTemp : string;
begin
// ' ', ä, ö, ü, ß, [, ], (, ), : in EMail-Address

Result := (Trim(AEmailAddress) = '') or
(Pos(' ', AnsiLowerCase(AEmailAddress)) > 0) or
(Pos('ä', AnsiLowerCase(AEmailAddress)) > 0) or
(Pos('ö', AnsiLowerCase(AEmailAddress)) > 0) or
(Pos('ü', AnsiLowerCase(AEmailAddress)) > 0) or
(Pos('ß', AnsiLowerCase(AEmailAddress)) > 0) or
(Pos('[', AnsiLowerCase(AEmailAddress)) > 0) or
(Pos(']', AnsiLowerCase(AEmailAddress)) > 0) or
(Pos('(', AnsiLowerCase(AEmailAddress)) > 0) or
(Pos(')', AnsiLowerCase(AEmailAddress)) > 0) or
(Pos(':', AnsiLowerCase(AEmailAddress)) > 0);
if Result then Exit; // @ not in EMail-Address;

LIndex := Pos('@', AEmailAddress);
Result := (LIndex = 0) or (LIndex = 1) or (LIndex = Length(AEmailAddress));
if Result then Exit;

Result := (Pos('@', Copy(AEmailAddress, LIndex + 1, Length(AEmailAddress) - 1)) > 0);
if Result then Exit; // Domain <= 1
LTemp := Copy(AEmailAddress, LIndex + 1, Length(AEmailAddress));
Result := Length(LTemp) <= 1;
if Result then Exit;
LIndex := Pos('.', LTemp);
Result := (LIndex = 0) or (LIndex = 1) or (LIndex = Length(LTemp));
end;

This piece of code proved to be very handy for me whenever I needed to validate the email address entered by user.

Until Next time.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. It would be more easier using regular expression component.

    ReplyDelete