I have one edittext and I would to to write email validation in my Editttext
this is a xml code
<EditText
android:id="#+id/mail"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignLeft="#+id/phone"
android:layout_below="#+id/phone"
android:layout_marginRight="33dp"
android:layout_marginTop="10dp"
android:background="#drawable/edit_background"
android:ems="10"
android:hint="E-Mail"
android:inputType="textEmailAddress"
android:paddingLeft="20dp"
android:textColor="#7e7e7e"
android:textColorHint="#7e7e7e" >
</EditText>
and this is a java code
emailInput = mail.getText().toString().trim();
emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
if (emailInput.matches(emailPattern)) {
Toast.makeText(getActivity(), "valid email address", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Invalid email address", Toast.LENGTH_SHORT).show();
mail.setBackgroundResource(R.drawable.edit_red_line);
}
I can't validation. The toast message is always "Invalid email address".
What am I doing wrong?
Why not use:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
As suggested here.
I am posting very simple and easy answer of email validation without using any string pattern.
1.Set on click listener on button....
button_resetPassword.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CharSequence temp_emilID=username.getText().toString();//here username is the your edittext object...
if(!isValidEmail(temp_emilID))
{
username.requestFocus();
username.setError("Enter Correct Mail_ID ..!!");
or
Toast.makeText(getApplicationContext(), "Enter Correct Mail_ID", Toast.LENGTH_SHORT).show();
}
else
{
correctMail..
//Your action...
}
});
2.call the isValidEmail() i.e..
public final static boolean isValidEmail(CharSequence target)
{
if (TextUtils.isEmpty(target))
{
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
I hope it will helpful for you...
Android Email Validation Simplest way
String validemail= "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+";
String emal=email.getText().toString();
Matcher matcherObj = Pattern.compile(validemail).matcher(emal);
if (matcherObj.matches()) {
Toast.makeText(getApplicationContext(), "enter
all details", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"please enter
valid email",Toast.LENGTH_SHORT).show();
}
Try following code:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
This works fine.
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if(emailId.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"enter email address",Toast.LENGTH_SHORT).show();
else {
if (emailId.getText().toString().trim().matches(emailPattern)) {
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}
}
here is a whole code for login validations......
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
#Bind(R.id.input_email) EditText _emailText;
#Bind(R.id.input_password) EditText _passwordText;
#Bind(R.id.btn_login) Button _loginButton;
#Bind(R.id.link_signup) TextView _signupLink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Signup activity
Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
startActivityForResult(intent, REQUEST_SIGNUP);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
});
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) {
// TODO: Implement successful signup logic here
// By default we just finish the Activity and log them in automatically
this.finish();
}
}
}
#Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
}
Use this function for validating email id:
private boolean validateEmaillId(String emailId){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(emailId).matches();
}
I had a query in email pattern for more than one Email ID validation and for only one Email ID.I solved it by using :
public static final String patter_emails="^(\\s*,?\\s*[0-9a-za-z]([-.\\w]*[0-9a-za-z])*#([0-9a-za-z][-\\w]*[0-9a-za-z]\\.)+[a-za-z]{2,9})+\\s*$";
public static final String patter_email="^(\\s*[0-9a-za-z]([-.\\w]*[0-9a-za-z])*#([0-9a-za-z][-\\w]*[0-9a-za-z]\\.)+[a-za-z]{2,9})+\\s*$";
These above is used for pattern in Java and Android both.
check this by using:
pattern test: rubular.com
android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()
private void isValidEmail(String email_id) {
if (email_id == null){
checkTextView.setVisibility(View.VISIBLE);
checkTextView.setText(LocaleController.getString("EnterValidEmail", R.string.EnterValidEmail));
return;
}
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email_id).matches()) {
checkTextView.setVisibility(View.GONE);
} else {
checkTextView.setVisibility(View.VISIBLE);
checkTextView.setText(LocaleController.getString("EnterValidEmail", R.string.EnterValidEmail));
}
Take a textView ex.checkTextView and validate when the email is valid then the textview is gone otherwise it show the message
Try this code
String emailPattern = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
if (!tvEmail.matches(Constants.emailPattern)){
tvEmail.setError("Invalid Email ");
}
else{
//your code
}
String emailPattern = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
if (!"anan.pp#gmail.co".matches(Constants.emailPattern)){
//tvEmail.setError("Invalid Email ");
} else {
// your code
}
Try below code:
Just call below method like,
if(emailValidator(mail.getText().toString())){
Toast.makeText(getActivity(), "valid email address",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "invalid email address",
Toast.LENGTH_SHORT).show();
}
public static boolean emailValidator(final String mailAddress) {
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(mailAddress);
return matcher.matches();
}
Assign a String variable to store the value of this EditText:
emailInput = mail.getText().toString().trim();
Use setError in your EditText:
if(!isValidEmail(emailInput)){
mail.setError("Invalid"); /*"Invalid Text" or something like getString(R.string.Invalid)*/
mail.requestFocus();
}
Create a method to check the email:
private boolean isValidEmail(String emailInput) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(emailInput);
return matcher.matches();
}
Related
When I run the codes, it does not show any error. I have no problem to login as guardian but when I try to login as elderly it couldn't and I don't know what's the problem. What I want is when a user input the username and password, it will validate from database and direct the user according to different user type.
Segment codes of Login.java:
private Boolean validateUsername() {
String val = username.getEditText().getText().toString();
if (val.isEmpty()) {
username.setError("Field cannot be empty");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = password.getEditText().getText().toString();
if (val.isEmpty()) {
password.setError("Field cannot be empty");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void loginUser(View view) {
//validate login info
if (!validateUsername() || !validatePassword()) {
return;
} else {
isUser();
}
}
private void isUser() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("user").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String input1 = username.getEditText().getText().toString();
String input2 = password.getEditText().getText().toString();
if (dataSnapshot.child(input1).exists()) {
if (dataSnapshot.child(input1).child("password").getValue(String.class).equals(input2)) {
if (active.isChecked()) {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Guardian");
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Elderly");
startActivity(new Intent(Login.this, dashboardUser.class));
}
} else {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardUser.class));
}
}
} else {
password.setError("Wrong Password");
password.requestFocus();
}
} else {
username.setError("No such User exist");
username.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onStart() {
super.onStart();
if (preferences.getDataLogin(this)) {
if (preferences.getDataAs(this).equals("Guardian")) {
startActivity(new Intent(this, dashboardGuardian.class));
finish();
} else {
startActivity(new Intent(this, dashboardUser.class));
finish();
}
}
}
}
Codes of Register.java:
public class Register extends AppCompatActivity {
//Variables
TextInputLayout regUsername, regEmail, regPhoneNo, regPassword;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;
UserHelperClass helperClass;
int i = 0;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Hooks to all xml elements in activity_register.xml
regUsername = findViewById(R.id.reg_username);
regEmail = findViewById(R.id.reg_email);
regPhoneNo = findViewById(R.id.reg_phoneNo);
regPassword = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regToLoginBtn = findViewById(R.id.reg_login_btn);
radioGroup = findViewById(R.id.radio_type);
selectedGuardian = findViewById(R.id.radioGuardian);
selectedElderly = findViewById(R.id.radioElderly);
helperClass = new UserHelperClass();
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
} else {
validateUsername();
validateEmail();
validatePhoneNo();
validateUserType();
validatePassword();
}
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("user");
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
String username = regUsername.getEditText().getText().toString();
String password = regPassword.getEditText().getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(username).setValue(helperClass);
}
});
regToLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
}
});
}
private Boolean validateUsername() {
String val = regUsername.getEditText().getText().toString();
String noWhiteSpace = "\\A\\w{4,20}\\z";
if (val.isEmpty()) {
regUsername.setError("Field cannot be empty");
return false;
} else if (val.length() >= 15) {
regUsername.setError("Username too long");
return false;
} else if (!val.matches(noWhiteSpace)) {
regUsername.setError("White space is not allowed");
return false;
} else {
regUsername.setError(null);
regUsername.setErrorEnabled(false);
return true;
}
}
private Boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else {
regEmail.setError(null);
return true;
}
}
private Boolean validatePhoneNo() {
String val = regPhoneNo.getEditText().getText().toString();
if (val.isEmpty()) {
regPhoneNo.setError("Field cannot be empty");
return false;
} else {
regPhoneNo.setError(null);
return true;
}
}
private Boolean validateUserType() {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please select user type", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
}
private Boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white space
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
public void registerUser(View view) {
if (!validateUsername() | !validatePassword() | !validatePhoneNo() | !validateEmail() | validateUserType()) {
return;
}
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(String.valueOf(i + 1)).setValue(helperClass);
}
}
Database structure
If you post your database structure that would be more helpful.
As per your code.
you have two children in input1
'radioGuardian' and 'radioElderly'
have you added both values on registration? Or it will be null. And it will produce nullPointEx.
Hence the issue is here!
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
Try to change it to:-
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
helperClass.setRadioGuardian("NA");
} else {
helperClass.setRadioGuardian(m2);
helperClass.setRadioElderly("NA");
}
I have made a fragment in which I am validating a Register form, it works fine sometime but after few seconds the app stops without showing any message nor I have any error log...I don't know what happens.
Here is my code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register, container, false);
RegUsername = (EditText) view.findViewById(R.id.RegUsername);
RegEmailId = (EditText) view.findViewById(R.id.RegEmailId);
RegPhoneNo = (EditText) view.findViewById(R.id.RegPhoneNo);
RegPassword = (EditText) view.findViewById(R.id.RegPassword);
RegisterButton = (Button) view.findViewById(R.id.Register);
RegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Register(); }})};
return view; }
private void Register() {
initialize();
if (!registerfail()) {
Toast.makeText(getActivity(), "Registration failed! || Try Again", Toast.LENGTH_SHORT).show();
} else {
registerok();
}
}
private void registerok() {
Toast.makeText(getActivity(), "Welcome " + Username, Toast.LENGTH_SHORT);
}
private boolean registerfail() {
boolean validation = true;
if (Username.isEmpty() || Username.length() > 25) {
RegUsername.setError("Invalid username");
validation = false;
}
if (EmailId.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(EmailId).matches()) {
RegEmailId.setError("Invalid EmailId");
validation = false; }
}
if (PhoneNo.isEmpty()) {
RegPhoneNo.setError("Invalid PhoneNo.");
validation = false; }
}
if (Password.isEmpty()) {
RegPassword.setError("Invalid Password");
validation = false;}
}
return validation; }
private void initialize() {
Username = RegUsername.getText().toString().trim();
EmailId = RegEmailId.getText().toString().trim();
PhoneNo = RegPhoneNo.getText().toString().trim();
Password = RegPassword.getText().toString().trim(); }}
//set validation = false if any if condition is failed
private boolean registerfail() {
boolean validation = true;
if (Username.isEmpty() || Username.length() > 25) {
RegUsername.setError("Invalid username");
validation = false;
}
if (EmailId.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(EmailId).matches()) {
RegEmailId.setError("Invalid EmailId");
validation = false;
}
if (PhoneNo.isEmpty()) {
RegPhoneNo.setError("Invalid PhoneNo.");
validation = false;
}
if (Password.isEmpty()) {
RegPassword.setError("Invalid Password");
validation = false;
}
return validation;
}
try this way my friend
String emailAddress = RegEmailId.getText().toString().trim();
if (RegPassword.getText().toString().length() < 6) {
RegPassword.setError(getString("password minimum contain 6 character"));
RegPassword.requestFocus();
}
if (RegPassword.getText().toString().equals("")) {
RegPassword.setError(getString("please enter password"));
RegPassword.requestFocus();
}
if (RegPhoneNo.getText().toString().equals("")) {
RegPhoneNo.setError(getString("please enter password"));
RegPhoneNo.requestFocus();
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches()) {
RegEmailId.setError(getString("please enter valid email address"));
RegEmailId.requestFocus();
}
if (RegEmailId.getText().toString().equals("")) {
RegEmailId.setError(getString("please enter email address"));
RegEmailId.requestFocus();
}
if (!emailAddress.equals("") &&
RegPassword.getText().toString().length() >= 6 &&
!RegPassword.getText().toString().trim().equals("")
&& android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches() &&
!RegPhoneNo.getText().toString().equals("")&&
RegPhoneNo.getText().toString().length()>=10) {
// do your action
}
I have an Email EditText and i want to check it using email validation.
This's my email validation code
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public void showAlertValidation() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(RegisterActivity.this);
alertDialog.setTitle("Failed");
alertDialog.setMessage("Invalid Email");
alertDialog.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
And this is my EditText validation code
editTextEmail= (EditText) findViewById(R.id.editTextEmail);
email = editTextEmail.getText().toString();
if(email.length() == 0) {
editTextEmail.setError("Email required!");
if (isValidEmail(email)) {
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else{
showAlertValidation();
}
}
The problem is the result of the EditText. When the value of EditText is null, it run showAlertValidation();
But if the value of EditText is "email" or "email#example" or "email#example.com", it not run showAlertValidation();
Anything wrong with my code?
We have a simple Email pattern matcher now
Java:
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Kotlin Function:
private fun isValidEmail(email: String): Boolean {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Kotlin Extension:
fun String.isValidEmail() =
!TextUtils.isEmpty(this) && Patterns.EMAIL_ADDRESS.matcher(this).matches()
You are mistakenly comparing your EditText text length to 0, and only if it's true, you do your validation logic.
Here is is the correct code:
#Override
public void onClick(View v) {
String email = editTextEmail.getText().toString();
if(email.length() != 0) {
if (isValidEmail(email)) {
Toast.makeText(getApplicationContext(), "Valid email address!", Toast.LENGTH_SHORT).show();
}
else{
editTextEmail.setError("Email required!");
showAlertValidation();
}
}
else{
editTextEmail.setError("Email required!");
}
}
Its better to make a class which validates the email. So that you can reuse it anywhere you need. You don't even need to put the text of edittext in separate string. Make the following class:
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static EmailValidator sInstance;
public static EmailValidator getInstance() {
if (sInstance == null) {
sInstance = new EmailValidator();
}
return sInstance;
}
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}}
Now use this class to check for validation of email of edittext like this:
if(!EmailValidator.getInstance().validate(editTextEmail.getText().toString().trim())){
editTextEmail.setError("Invalid email address");
}
Hope this helps.
you should clear space " " before check length of email string with String.trim();
if(email.trim().length() == 0) {//code here}
Problem is your if condition
if(email.length() == 0)
{
editTextEmail.setError("Email required!");
if (isValidEmail(email))
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else
{
showAlertValidation();
}
}
As it only validates your email address when your editText is empty.
What you can do is :
email.addTextChangedListener(new TextWatcher()
{
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
if(s.length() > 0)
{
if (isValidEmail(email))
{
editTextEmail.setError(null);
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"valid email address Required",Toast.LENGTH_SHORT).show();
}
}
}
});
I think this is where you made a mistake (EditText validation code):
editTextEmail= (EditText) findViewById(R.id.editTextEmail);
email = editTextEmail.getText().toString();
if(email.length() == 0) {
editTextEmail.setError("Email required!");
}
else if (isValidEmail(email)) {
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else{
showAlertValidation();
}
Hi In My application checking validation for email id and phone number but it's not validating both and simply it's saving into database.
I want to check the email id and phone number if it's both correct i want to do next process
Can any one please help me
ContactUs.java
public class ContactUs extends Activity
{
EditText fname1,lname1,mobile1,altmob1,email1,comment1;
String data="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1=(EditText) findViewById(R.id.fname);
lname1=(EditText) findViewById(R.id.lname);
mobile1=(EditText) findViewById(R.id.mobile);
altmob1=(EditText) findViewById(R.id.altno);
email1=(EditText) findViewById(R.id.email);
comment1=(EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
String fname = fname1.getText().toString();
String lname = lname1.getText().toString();
String mobile = mobile1.getText().toString();
String altmob = altmob1.getText().toString();
String email = email1.getText().toString();
String comment = comment1.getText().toString();
if(fname.equals(""))
{
fname1.setError( "Please Enter First Name" );
}
else if(lname.equals(""))
{
lname1.setError( "Please Enter Last Name" );
}
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
else if(altmob.equals(""))
{
altmob1.setError( "Please Enter Altenative Mobile No." );
}
else if(email.equals(""))
{
email1.setError( "Please Enter EmailId" );
isValidMail(email);
}
else if(comment.equals(""))
{
comment1.setError( "Please Enter Your Comments here" );
}
else
{
try{
String queryString ="fname="+ fname
+"&lname="+lname+"&mobile="+mobile+ "&altmob="+altmob+"&email="+email+"&comment="+comment;
data = DatabaseUtility.executeQueryPhp("Contactform",queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private boolean isValidMail(String email)
{
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
if(!check)
{
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile)
{
boolean check;
if(mobile.length() < 6 || mobile.length() > 13)
{
check = false;
mobile1.setError("Not Valid Number");
}
else
{
check = true;
}
return check;
}
there are edittext box with property email
android:inputType="textEmailAddress"
in your code
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
it check if email in blank then go to isValidMobile
so use
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile)){
// do somting
}
and similar for email
You are running your valid email check but ignoring the result. As long as you enter some text the call to save will work.
If you incorporate the return values from your is valid check methods, you can stop saving when those calls return false.
e.g.
if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile))
{
mobile1.setError("Not Valid Number");
}
Try this for checking email:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
For telephone number check:
public final static boolean isValidPhone(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
And please update your code with as :
public class ContactUs extends Activity {
EditText fname1, lname1, mobile1, altmob1, email1, comment1;
String data = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1 = (EditText) findViewById(R.id.fname);
lname1 = (EditText) findViewById(R.id.lname);
mobile1 = (EditText) findViewById(R.id.mobile);
altmob1 = (EditText) findViewById(R.id.altno);
email1 = (EditText) findViewById(R.id.email);
comment1 = (EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String fname = fname1.getText().toString().trim();
String lname = lname1.getText().toString().trim();
String mobile = mobile1.getText().toString().trim();
String altmob = altmob1.getText().toString().trim();
String email = email1.getText().toString().trim();
String comment = comment1.getText().toString().trim();
if (fname.length() != 0) {
if (lname.length() != 0) {
if (mobile.length() != 0 && isValidMobile(mobile)) {
if (altmob.length() != 0 && isValidMobile(altmob)) {
if (email.length() != 0 && isValidMail(email)) {
if (comment.length() != 0) {
try {
String queryString = "fname="
+ fname + "&lname=" + lname
+ "&mobile=" + mobile
+ "&altmob=" + altmob
+ "&email=" + email
+ "&comment=" + comment;
data = DatabaseUtility
.executeQueryPhp(
"Contactform",
queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
comment1.setError("Please Enter Your Comments here");
}
} else {
email1.setError("Please Enter Valid EmailId");
}
} else {
altmob1.setError("Please Enter Altenative Mobile No.");
}
} else {
mobile1.setError("Please Enter valid Mobile No.");
}
} else {
lname1.setError("Please Enter Last Name");
}
} else {
fname1.setError("Please Enter First Name");
}
}
});
}
private boolean isValidMail(String email) {
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
if (!check) {
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile) {
boolean check;
if (mobile.length() < 6 || mobile.length() > 13) {
check = false;
mobile1.setError("Not Valid Number");
} else {
check = true;
}
return check;
}
}
I wrote following code for login but when I type "\" after email-id, it accepts and log in successfully (it doesn't accepts any other symbols or characters only accepts "\").
I don't want that it login with "\".`
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.main);
WiztangoBaseApplication.InitDialogBox(WiztangoActivity.this);
this.pref = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.login_status);
register = (Button) findViewById(R.id.btnregister);
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RegisterIntent();
}
});
login = (Button) findViewById(R.id.btlogin);
password = (EditText) findViewById(R.id.txtPwd);
username = (EditText) findViewById(R.id.txtemail);
saveLoginCheckBox = (CheckBox)findViewById(R.id.saveLoginCheckBox);
pref = getSharedPreferences(Constants.PREFS_NAME,
MODE_PRIVATE);
String usernamestr = pref.getString(Constants.PREF_USERNAME, "");
String passwordsharestr = pref.getString(Constants.PREF_PASSWORD,
"");
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLogin = pref.getBoolean("saveLogin", false);
if (saveLogin == true) {
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLoginCheckBox.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
//Constants.clearInfo();
getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(Constants.PREF_USERNAME,
username.getText().toString())
.putString(Constants.PREF_PASSWORD,
password.getText().toString())
.putString(Constants.PREF_CHECKED, "TRUE")
.commit();
if (username.getText().toString().trim().equals("")) {
username.setError(Html
.fromHtml("Please Enter Username"));
username.requestFocus();
} else if (password.getText().toString().trim()
.equals("")) {
password.setError(Html
.fromHtml("Please Enter Password"));
password.requestFocus();
} else {
if (Constants
.checkInternetConnection(WiztangoActivity.this)) {
Constants.userpass = password.getText()
.toString();
new AuthenticData().execute();
} else {
WiztangoBaseApplication.ShowThisDialog("Error",
"Please check internet connection.");
}
if (saveLoginCheckBox.isChecked()) {
prefEditor.putBoolean("saveLogin", true);
prefEditor.putString(Constants.PREF_USERNAME,
username.getText().toString());
prefEditor.putString(Constants.PREF_PASSWORD,
password.getText().toString());
saveLoginCheckBox.setChecked(true);
prefEditor.commit();
} else {
SharedPreferences mPreferences = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor=mPreferences.edit();
editor.remove(Constants.PREF_USERNAME);
editor.remove(Constants.PREF_PASSWORD);
editor.commit();
}
}
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
Inbuilt Patterns Provides Email Validation like:
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailStr).matches() && !TextUtils.isEmpty(emailStr)) {
emailEditText.setError("Invalid Email");
emailEditText.requestFocus();
}
Heyy, check this answer here: https://stackoverflow.com/a/7882950/1739882
It says:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
You can use this code for check is Valid Email or not:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Best Approach
Validate email and isEmpty in one method.
public final static boolean isValidEmail(CharSequence target)
{
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
Try out the below method to validate the Email address.
private boolean validateEmail(EditText editText, String p_nullMsg, String p_invalidMsg)
{
boolean m_isValid = false;
try
{
if (p_editText != null)
{
if(validateForNull(editText,p_nullMsg))
{
Pattern m_pattern = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+#([\\w\\-]+\\.)+[A-Za-z]{2,4})");
Matcher m_matcher = m_pattern.matcher(editText.getText().toString().trim());
if (!m_matcher.matches() && editText.getText().toString().trim().length() > 0)
{
m_isValid = false;
editText.setError(p_invalidMsg);
}
else
{
m_isValid = true;
}
}
else
{
m_isValid = false;
}
}
else
{
m_isValid = false;
}
}
catch(Throwable p_e)
{
p_e.printStackTrace(); // Error handling if application crashes
}
return m_isValid;
}
Try this code:--
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}