Android check if an email address is valid or not? - java

I develop an android app that can send emails to users.
But it turned out that some email addresses are not valid.
How check if the email address entered by the user is valid or not?

if you want check validate of email you can use:
public static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
but there is no way to find out what email address is real
you can use following method for removing if/else.
public static boolean isValidEmail(CharSequence target) {
return target != null && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

This code works totally fine and it gives you a boolean value. So if its true it will give true and false it will give you false
android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();

Probably the best way to check if the email is real, is to actually send an email to that address with a verification code/link that will activate that user on your site. Using regular expressions will only make sure the email is valid, but not necessarily real.

You can use a Regular expression to validate an email address, so:
public boolean isEmailValid(String email)
{
final String EMAIL_PATTERN =
"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
final Pattern pattern = Pattern.compile(EMAIL_PATTERN);
final Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
Here is a link with more RegExes to choose from.

There is no way of checking email is real or not. But You can check only the validation that is it in correct format or not.

There is no way to know if an email exists or not. Specially if it is on a site like yopmail or similar, which I believe would accept any mail to any account on their domain.
However, you can check:
1. if the address has the correct syntax and is on a registered domain (regex for syntax and a dns check if there is a mailserver for the site behind the #)
2. send an e-mail and check the response, some providers might send you back an error if the mail is not registered on their site.

Use below code:
if(validateEmail(mEdtTxtEmail.getText().toString().trim())){
// your code
}
private boolean validateEmail(String data){
Pattern emailPattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher emailMatcher = emailPattern.matcher(data);
return emailMatcher.matches();
}

Use :
if (!Patterns.EMAIL_ADDRESS.matcher(your_edit_text.getText().toString()).matches()){
loginEmail.setError("Please enter a Valid E-Mail Address!");
}else {
//email is valid
}

Here is a Kotlin version using Kotlin Extensions (extending the String object, so you can call stringName.isValidEmail():
fun String.isValidEmail(): Boolean {
return android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}

Related

Exceptions or null in java

I have the next doubt. According to good practices of java, how to manage the cases in which the object can not be found and we want to know why.
For example, if someone has problems logging in our system and we want to inform them exactly what is the problem, we cannot return null because we lose the reason for not being able to log in. For example:
public User login(String username, String password) {
boolean usernameEmpty = (credentials.getUsername()==null || credentials.getUsername().isEmpty());
boolean passwordEmpty = (credentials.getPassword()==null || credentials.getPassword().isEmpty());
//getUserPassword return null if doesn't exist an user with username and password return null
User user = getUserPassword(username,password);
if (!usernameEmpty && !passwordEmpty && user!=null) {
LOGGER.info("Found " + username);
} else if (!usernameEmpty && !passwordEmpty && user==null) {
LOGGER.info("There is no such username and password: " + username);
} else if (usernameEmpty) {
LOGGER.info("Username can not be empty ");
} else if (passwordEmpty) {
LOGGER.info("Password can not be empty ");
}
return user;
}
I can think of two options with pros and cons to resolve it.
The first one consists in using Exceptions but I think that is not a good idea use different scenarios than expected like exceptions. For that reason, I discard it.
The second one is involve the object (User) in another object to manage the differents posibilities. For example, use something like this:
public class EntityObject<t> {
//Is used to return the entity or entities if everything was fine
private t entity;
//Is used to inform of any checked exception
private String exceptionMessage;
//getters / setters / ..
}
public EntityObject<User> login(String username, String password) {
boolean usernameEmpty = (credentials.getUsername()==null || credentials.getUsername().isEmpty());
boolean passwordEmpty = (credentials.getPassword()==null || credentials.getPassword().isEmpty());
User user = getUserPassword(username,password);
EntityObject<User> entity = null;
if (!usernameEmpty && !passwordEmpty && user!=null) {
LOGGER.info("Found " + username);
entity = new EntityObject<User>(user);
} else if (!usernameEmpty && !passwordEmpty && user==null) {
entity = new EntityObject<User>("There is no such username and password: " + username);
} else if (usernameEmpty) {
entity = new EntityObject<User>("Username can not be empty ");
} else if (passwordEmpty) {
entity = new EntityObject<User>("Password can not be empty ");
}
return entity;
}
I like more this second option than the first one but i don't like that i have to change the method signature to return a different class (EntityObject) than the usual (User).
What is the usual? How is it usually managed?
many thanks
An exception should be used when there is something exceptional happening in the system. For a normal flow and something that is expected to happen you should avoid using exceptions.
Following the good SOLID principals your method should do just one thing. So if it is a method to find user by username and password I would say the best would be to return null (or empty optional if using optionals). The reason is not lost. Actually it is pretty clear - there is not such user found with the supplied username and password (this reason includes the problem with empty username and it's the user of the method's fault to supply empty username to a login method). Adding complex logic to the method and additional entities for such things will make your code harder to maintain and to understand. This method's job is not to handle validation anyway.
If that class is used by a website or its some kind of API then they can handle the validation (if username or password is empty).
For me, second options look better. Probably, to know what was the error instead of writing messages in java code, you can create enum with possible scenarios and resolve it in the Front-end code, if you really need a message, you can create constructor inside enum to store it. It will simplify support and work with an object in the future. Plus, adding more scenarios will not hurt you much.
Basic version:
public class EntityObject<t> {
//Is used to return the entity or entities if everything was fine
private t entity;
//Is used to inform of any checked exception
private enum auth {
NO_PASSWORD, NO_USERNAME, USER_DOES_NOT_EXIST, SUCCESS
}
}
Version with enum constructor:
public class EntityObject<t> {
//Is used to return the entity or entities if everything was fine
private t entity;
//Is used to inform of any checked exception
private enum auth {
NO_PASSWORD("Password cannot be empty"),
NO_USERNAME("Username cannot be empty"),
USER_OR_PASSWORD_DOES_NOT_EXIST("No such username or password exist"),
SUCCESS("OK");
public String message;
public auth(String message) {
this.message = message;
}
}
}
I would say that the second approach is pretty fine. If I were you I would do that.
If you really don't want to change the return value, you can add another method that checks if a user can log in:
public static final String SUCCESS = "Success"
public String checkLoginError(String username, String password) {
// do all the checks and return the error message
// return SUCCESS if no error
}
Now the login method can then be one line:
return getUserPassword(username,password);
And you can use it like this:
String loginResult = checkLoginError(...);
if (loginResult.equals(SUCCESS)) {
User loggedInUser = login(...)
} else {
// do stuff with the error message stored in loginResult
}
It seems like your problem is stemming from a method which is responsible for multiple concerns.
I'd argue that the login method shouldn't be checking whether these values are blank. There is presumably some kind of UI (graphical or not) which is taking a username and password - this should be the layer performing validation on the user input.
The login method should only be concerned with whether the given credentials match a user in your system or not. There's only two outcomes - yes or no. For this purpose, you can use Optional<User>. It should tolerate the strings being empty as this will never match a user anyway (presumably it's impossible for a user to exist in such a state).
Here's some pseudo-code:
void loginButtonPressed()
{
if (usernameTextBox.text().isEmpty())
{
errorPanel.add("Username cannot be blank");
}
else if (passwordTextBox.text().isEmpty())
{
errorPanel.add("Password cannot be blank");
}
else
{
login(usernameTextBox.text(), passwordTextBox.text());
// assign above result to a local variable and do something...
}
}
public Optional<User> login(String username, String password)
{
Optional<User> user = Optional.ofNullable(getUserPassword(username, password));
user.ifPresentOrElse(
user -> LOGGER.info("Found " + username),
() -> LOGGER.info("Not found")
);
return user;
}
Java's null values are one of the worst aspects of the language, as you cannot really tell if a method is receiving a null value until it happens. If you are using an IDE (I hope so) you can check if it can control whether you are passing a null value where there shouldn't be one (IntelliJ can do this by adding the #NotNull annotation to the method's parameters).
Since it can be dangerous, it is better to avoid passing nulls around, as it will certainly lead to an error as soon as your code gets a bit complex.
Also, I think it would be reasonable to check for null values only if there is a concrete chance that there could be one.
If you want to express that a value can be present or not, it's better to use Optional<T>. If, for some reason, a null value could be passed instead of a real value, you could create an utility method whose only concern is to verify that the parameters are correct:
public Optional<EntityObject<User>> login(String username, String password) {
//isNotNull shouldn't be necessary unless you can't validate your parameters
//before passing them to the method.
//If you can, it's not necessary to return an Optional
if (isNotNull(username, password)) {
//Since I don't know if a password must always be present or not
//I'm assuming that getUserPassword returns an Optional
return Optional.of(new EntityObject<User>(getUserPassword(username,password).orElse(AN_EMPTY_USER)));
} else {
return Optional.Empty();
}
}
Anyway, I think that validating the input shouldn't be a concern of the login method, even if you don't want to use Optional; it should be done in another method instead.

check whether data available in orm database

Is it possible to add the data in to the sugarorm db by this method? I want to validate if the user is already in db, if yes then display "user available" else I want to insert the value in the database.Can some one help me with this validation?
private void postDataToSQLite() {
User.find(User.class, "email = ? and password = ?", email, password);
You Need to change the if condition. You are currently checking the user already exits or not. But issue is you trying compare two string using "==" this. But if you need to compare two string you have to use "equals"
Current Code
if (user.getEmail() != textInputEditTextEmail.getText().toString().trim() || user.getPassword() != textInputEditTextPassword.getText().toString().trim()) {
New Code
if (!user.getEmail().equals(textInputEditTextEmail.getText().toString().trim()) || !user.getPassword().equals(textInputEditTextPassword.getText().toString().trim()) ) {

Java Method to Check if URL Fits Pattern

I have the need to do some primitive url matching in java. I need a method that will return true, saying
/users/5/roles
matches
/users/*/roles
Here is what I am looking for and what I tried.
public Boolean fitsTemplate(String path, String template) {
Boolean matches = false;
//My broken code, since it returns false and I need true
matches = path.matches(template);
return matches;
}
One option is to replace the * with some kind of regex equivalent such as [^/]+, but the kind of pattern being used here is actually called a "glob" pattern. Starting in Java 7, you can use FileSystem.getPathMatcher to match file paths against glob patterns. For a complete explanation of the glob syntax, see the documentation for getPathMatcher.
public boolean fitsTemplate(String path, String template) {
return FileSystems.getDefault()
.getPathMatcher("glob:" + template)
.matches(Paths.get(path));
}

if username and password combination are correct by checkin the google datastore

Edit: Apparently the question wasn't clear so...
How do I find the password for a user in the datastore and check if it is equal to the password given to the method if that makes sense.
end of edit.
I have the following code for checking if the username exists, now I just need to check the password is correct for the given username.
public boolean Login(String usernamein, String passwordin) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter usernamefilter = new FilterPredicate("username", FilterOperator.EQUAL, usernamein);
Query validuserquery = new Query("Users").setFilter(usernamefilter).setKeysOnly();
Entity theUser = datastore.prepare(validuserquery).asSingleEntity();
System.out.println(usernamein);
System.out.println(validuserquery);
System.out.println(theUser);
if(theUser == null) {
System.out.println("Username not found");
return false;
}
return true;
}
I am struggling to work out how I would do this even as pseudo code and I am really new to GAE and datastore but its for my A-Levels
I thought this addition would do it but theUser.getProperty("password") is null i don't really know what the user is in this code but i do know all the users in my data store have a password so none of them should be null
if(theUser == null) {
System.out.println("Username not found");
return false;
}
System.out.println(theUser.getProperty("password"));
if(passwordin.equals(theUser.getProperty("password"))){
return true;
}
return false;
If anything doesnt make sense or if you need more info tell me please as i do really need help :(
The setKeysOnly was my suggestion on a separate Q (and you haven't accepted my A there so it's, ahem, peculiar to see you use it here!) where you wanted just to check if the username was present or not.
With that you don't get any properties.
Remove it and the properties will be there (in your first Q you had a projection, which is fine if your user entity is large and you only need the password property out of many -- but it's an optimization, just like setKeysOnly is, and you hopefully know the rule -- first make it work, then make it fast!-).

Non-Confusing Simple Validation of email in Java String

I am trying to find a simple method to check to see if a user's input meets a couple criteria for an email address. I've read through many threads on this subject and most seem to want to validate the email address too. I'm not trying to build some super duper email address validator/checker. I'm trying to build a method that checks for these things:
The string entered by the user contains the '#' sign.
There are at least two characters before the '#' sign.
There is a '.' after the at sign followed by only three characters. The domain name can be as long as needed, but the string must end with "._ _ _". As in ".com" or ".net"...
I understand that this is not an all encompassing email address checker. That's not what I want though. I want just something this simple. I know that this is probably a routine question but I can't figure it out even after reading all of the seriously crazy ways of validating an email address.
This is the code I have so far: (Don't worry I already know it's pretty pathetic.... )
public static void checkEmail()
{
validEmail(emailAddresses);
if(validEmail(emailAddresses))
{
}
}
public static boolean validEmail(String email) {
return email.matches("[A-Z0-9._%+-][A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{3}");
}
The javax.mail package provides a class just for this: InternetAddress. Use this constructor which allows you to enforce RFC822 compliance.
Not perfect, but gets the job done.
static boolean validEmail(String email) {
// editing to make requirements listed
// return email.matches("[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}");
return email.matches("[A-Z0-9._%+-][A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{3}");
}
void checkEmails() {
for(String email : emailAddresses) {
if(validEmail(email)) {
// it's a good email - do something good with it
}
else {
// it's a bad email - do something... bad to it? sounds dirty...
}
}
}
int indexOfAt = email.indexOf('#');
// first check :
if (indexOfAt < 0) {
// error
}
// second check :
if (indexOfAt < 2) {
// error
}
// third check :
int indexOfLastDot = email.lastIndexOf('.');
if (indexOfLastDot < indexOfAt || indexOfLastDot != (email.length() - 4)) {
// error
}
Read http://download.oracle.com/javase/6/docs/api/java/lang/String.html for the documentation of the String methods.

Categories

Resources