r.r
r.r

Reputation: 7153

validate that an email address contains "@" and "."

i need to validate that an inserted email address contains "@" and "." without a regular expression. Can somebody to give me "java code" and "structure chart" examples please?

Upvotes: 2

Views: 16938

Answers (7)

Sachin
Sachin

Reputation: 18747

int dot = address.indexOf('.');
int at = address.indexOf('@', dot + 1);

if(dot == -1 || at == -1 || address.length() == 2) {
  // handle bad address
}

This is not complete solution. You will have to check for multiple occurances of @ and address with only '.' and '@'.

Upvotes: 1

Santiago V.
Santiago V.

Reputation: 1118

You can search for the first '@', then check if what you have at the left of the '@' is a valid string (i.e. it doesn't have spaces or whatever). After that you should search in the right side for a '.', and check both strings, for a valid domain.

This is a pretty weak test. Anyway I recommend using regular expressions.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500245

I suspect you're after something like:

if (!address.contains("@") || !address.contains("."))
{
    // Handle bad address
}

EDIT: This is far from a complete validation, of course. It's barely even the start of validation - but hopefully this will get you going with the particular case you wanted to handle.

Upvotes: 10

Nathan Ryan
Nathan Ryan

Reputation: 13041

You can also use the Java Mail API. Specifically, here:

http://javamail.kenai.com/nonav/javadocs/javax/mail/internet/InternetAddress.html#InternetAddress(java.lang.String, boolean)

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240880

You can use commons-validator , Specifically EmailValidator.isValid()

Upvotes: 3

VirtualTroll
VirtualTroll

Reputation: 3091

From my personal experience, the only was to validate an email address is to send a email with a validation link or code. I tried many of the validator but they are not complete because the email addresses can be very loose ...

Upvotes: 1

Kaj
Kaj

Reputation: 10949

Use String.indexOf if you aren't allowed to use regexp, and but I would adwise you to not validate the address during input.

It's better to send an activation email.

Upvotes: 0

Related Questions