Input Validation In Android
Solution 1:
You are getting an error because .matcher()
takes CharSequence
as argument but you are passing boolean
because value.matches()
returns boolean
.
So instead of
Patterns.EMAIL_ADDRESS.matcher(value.matches())
You should be doing
Patterns.EMAIL_ADDRESS.matcher(value).matches()
Solution 2:
Patterns.EMAIL_ADDRESS.matcher(value.matches()) does not return boolean value. in order to return boolean value you should use matches() method like below in the if statement
String value= textInputEditText.getText().toString().trim();
if (value.isEmpty() || Patterns.EMAIL_ADDRESS.matcher(value).matches())
Solution 3:
Create Util Class. Add isValidEmaillId Method in Util Class
publicstatic boolean isValidEmaillId(String email){
returnPattern.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(email).matches();
}
use this ur Actitty class
String Email= textInputEditText2.getText().toString().trim();
if (Email.isEmpty()|| !Util.isValidEmaillId(Email)){
Toast.makeText(this, "Must Enter Valid Email ",
Toast.LENGTH_SHORT).show();
return;
}
Solution 4:
you just have to take a global variable with some name like pattern match and after that you have to create an method and you can call that method anywhere where you have to validate the email. method will split the string and check whether it is matching the pattern or not if it is false it will generate error otherwise it will return the result true and based on that result you can do whatever your project need is. example is given below
/*take this as golabl variable*/privateString emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+\\.+[a-z]+";
/*in some method i have to validate that the entered email is valid or not*/boolean result = validateEmail();
validateEmail()
{
String email = textInputEditText.getText().toString().trim();
if (!email.isEmpty()) {
if (email.length() != 0) {
String data[] = cc.split(",");
for (int i = 0; i < data.length; i++) {
if (!email.matches(emailPattern)) {
textInputEditText.setError("Invalid");
returnfalse;
}
}
}
}
returntrue;
Post a Comment for "Input Validation In Android"