How to check edittext - android

I want to add a verification to my edit text:
check if the name is not a number
check if the tel is a number
check if the password and password2 are equals
How can I do this?
if (name.isEmpty() || name.length() < 3 || ............) {
et_name.setError("enter a valid name");
valid = false;
} else {
et_nom.setError(null);
}
if (tel.isEmpty() || ..........) {
et_tel.setError("enter a valid tel");
valid = false;
} else {
et_tel.setError(null);
}
if (password.isEmpty() || password2.isEmpty() || ..........) {
et_password.setError("enter a valid password");
valid = false;
} else {
et_password.setError(null);
}

Okey...
first :
for name you don't want allow user to enter numbers so what you can do is add two attributes to your name EditText.
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
android:inputType="text"
This will allow user to enter only alphabets and blank space. so no need for verification on that programmatically.
Second :
Same for the telephone number. you have to add android:inputType="number" to your telephone EditText. So user will able to input numbers only.
Third
for validating if your EditText is empty or not you can do following.
if (name.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
Fourth
For checking password equality you can do following.
if (!password1.getText().toString().equals(password2.getText().toString())) {
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
Now Hopefully you understand this whole process. for your case refer following code.
if (name.getText().toString().equals("") || name.length() < 3 ||) {
et_name.setError("enter a valid name");
valid = false;
}
if (tel.getText().toString().equals("")) {
et_tel.setError("enter a valid tel");
valid = false;
}
if (password.getText().toString().equals("") || password2.getText().toString().equals("") || !password.getText().toString().equals(password2.getText().toString())) {
et_password.setError("enter a valid password");
valid = false;
}
Happy coding.

Why not just set the inputType="number" of the EditText in the xml? If you still prefer checking it dynamically, check out this post.
TextUtils.equals() - http://developer.android.com/reference/android/text/TextUtils.html#equals(java.lang.CharSequence, java.lang.CharSequence)
Cheers! :D

Try using android.text.Utils.TextUtils class (part of android SDK)
See inputType
1. Check if name is number
if(TextUtils.isDigitsOnly(str)) {
//number
}
2. Check if name is not a number
if(!TextUtils.isDigitsOnly(str)) {
//number
}
3. Check if two password1 and password2 are equal
if(!TextUtils.isEmpty(password1) && !TextUtils.isEmpty(password2) && !password1.equals(password2)) {
//number
}

Related

FirstName field Validations in Android Studio

Sample code format
Hello everyone, I have added this line of code for validation to check whether the first name field contains numbers or special characters however, upon testing it it seems the firstname always shows error
can anyone pls help. big thanks!
(!isNetworkAvailable()) {
showSweetDialog(AppConstants.ERR_CONNECTION, "error", false, null, null);
} else if (firstName.isEmpty()) {
setError(etFirstName, AppConstants.WARN_FIELD_REQUIRED);
}
else if(!firstName.matches("[a-zA-Z]")){
setError(etFirstName, AppConstants.WARN_FIELD_REQUIRED);
}
else if (lastName.isEmpty()) {
setError(etLastName, AppConstants.WARN_FIELD_REQUIRED);
} else if (mobile.isEmpty()) {
setError(etMobile, AppConstants.WARN_FIELD_REQUIRED);
} else if (email.isEmpty()) {
setError(etEmail, AppConstants.WARN_FIELD_REQUIRED);
} else if (password.isEmpty()) {
setError(etPassword, AppConstants.WARN_FIELD_REQUIRED);
} else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
setError(etEmail, AppConstants.WARN_INVALID_EMAIL_FORMAT);
} else if (address.isEmpty()) {
setError(etAddress, AppConstants.WARN_FIELD_REQUIRED);
} else {
specify where the beginning and the end of the string is by adding ^ and $. Try it like that:
else if(!firstName.matches("^[A-Za-z]+$")){
setError(etFirstName, AppConstants.WARN_FIELD_REQUIRED);
}
which means:
^ beginning of the string,
[A-Za-z] search for alphabetical chars either they are CAPITALS or not
+ string contains at least one alphabetical char
$ end of the string
Now you should get the error message only if the first name contains some special or numerical characters.

Comparing two EditText values in android

I'm trying to make an app where the user enters a word into an EditText box. Then, they enter something into another box and it checks to see if they are the same word. Here's the code that I used:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
textfield2.setText(textfield2.getText().toString());
if(word == answer){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}
However, it always says that the two strings aren't the same even if they are. Is there a way to fix this?
You can't compare strings with the == operator.
Use .equals() instead:
if(word.equals(answer)) {
//do whatever
}
Use String.equalsIgnoreCase for comparing content of both string variables.:
if(word.equalsIgnoreCase(answer)){
}
Use:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(answer.contentEquals(word)){
// Do something if equals
}
else{
// Do something if not equals
}
I think the best way to do this is using TextUtils:
if(TextUtils.equals(textfield1.getText(),textfield2.getText())){
//do something
}
instead of
if(word.contentEquals(answer)){
}
Use
if(word.equals(answer))
as we cant compare strings with Equal to (==) operator
Try This::
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(word.equals(answer)){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}

How to Validate Phone Number format

i am about to create a validation for phone number format..The format is 10 digit including the plus sign eg:+0133999504. Even though I have declare the pattern which is I try to disallow the "-" symbol or any other characters, but the validation is not working. Any other Idea or solution?
1st I declared the string regex:
String PhoneNo;
String PhoneNo_PATTERN ="[\\+]\\d{3}\\d{7}";
2nd I make a if..else statement:
{
Pattern pattern = Pattern.compile(PhoneNo_PATTERN);
Matcher matcher = pattern.matcher(PhoneNo);
if (!matcher.matches())
{
inputemergencyContactNo.setError("Please enter Emergency Contact No");
}
else{
Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
}
Why not remove all non-digits and then count the digits left and put the plus back in later? This allows users the freedom to fill out their phone number anyway they want...
String PhoneNo = "+123-456 7890";
String Regex = "[^\\d]";
String PhoneDigits = PhoneNo.replaceAll(Regex, "");
if (PhoneDigits.length()!=10)
{
// error message
}
else
{
PhoneNo = "+";
PhoneNo = PhoneNo.concat(PhoneDigits); // adding the plus sign
// validation successful
}
If your app is intended for international use replace
if (!PhoneDigits.length()!=10)
with
if(PhoneDigits.length() < 6 || PhoneDigits.length() > 13)
as Fatti Khan suggested.
To apply this in the code you posted at Android EditText Validation and Regex first include this method in your public class or the class containing onClick():
public boolean validateNumber(String S) {
String Regex = "[^\\d]";
String PhoneDigits = S.replaceAll(Regex, "");
return (PhoneDigits.length()!=10);
}
And include this method in the CreateNewRider class:
protected String tidyNumber(String S) {
String Regex = "[^\\d]";
String PhoneDigits = S.replaceAll(Regex, "");
String Plus = "+";
return Plus.concat(PhoneDigits);
}
This is where the validation happens...
#Override
public void onClick(View view) {
Boolean b = false;
if(inputfullname.getText().toString().equals("")) b = true;
else if(... // do this for all fields
else if(inputmobileNo.getText().toString().equals("")) b=true;
else if(inputemergencyContactNo.getText().toString().equals("")) b=true;
else {
if(validateNumber( inputmobileNo.getText().toString() )
Toast.makeText(RiderProfile.this, "Invalid mobile number", Toast.LENGTH_SHORT).show();
else if(validateNumber( inputemergencyContactNo.getText().toString() )
Toast.makeText(RiderProfile.this, "Invalid emergency contact number", Toast.LENGTH_SHORT).show();
else {
// Validation succesful
new CreateNewRider().execute();
}
}
if(b) Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
}
And then use tidyNumber() in the CreateNewRider class:
protected String doInBackground(String... args) {
String fullname= inputfullname.getText().toString();
String IC= inputIC.getText().toString();
String mobileNo= tidyNumber( inputmobileNo.getText().toString() );
String emergencyContactName= inputemergencyContactName.getText().toString() );
String emergencyContactNo= tidyNumber( inputemergencyContactNo.getText().toString() );
...
Given the rules you specified:
upto length 13 and including character + infront.
(and also incorporating the min length of 10 in your code)
You're going to want a regex that looks like this:
^\+[0-9]{10,13}$
With the min and max lengths encoded in the regex, you can drop those conditions from your if() block.
Off topic: I'd suggest that a range of 10 - 13 is too limiting for an international phone number field; you're almost certain to find valid numbers that are both longer and shorter than this. I'd suggest a range of 8 - 20 to be safe.
[EDIT] OP states the above regex doesn't work due to the escape sequence. Not sure why, but an alternative would be:
^[+][0-9]{10,13}$
[EDIT 2] OP now adds that the + sign should be optional. In this case, the regex needs a question mark after the +, so the example above would now look like this:
^[+]?[0-9]{10,13}$
For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number . Also we can not check like mobile number must starts with 9 or 8 or anything..
For mobile number I used this this Function
private boolean isValidMobile(String phone2)
{
boolean check;
if(phone2.length() < 6 || phone2.length() > 13)
{
check = false;
txtPhone.setError("Not Valid Number");
}
else
{
check = true;
}
return check;
}
^[\\+]\\d{3}\\d{7}$
Use anchors to limit the match.
^ => start of match
$=> end of match
To validate India's mobile number.
Your edit text input
edt_mobile.text.toString().trim()
Number validation method
fun isValidMobile(phone: String): Boolean {
return phone.matches(Constants.REGEX_MOBILE.toRegex()) && phone.trim().length == 10
}
Regression expression
const val REGEX_MOBILE = "^[6-9]{1}[0-9]{9}\$"

how to do form validation in android

I have a registration form which I need to validate before submit. The form has the following fields:name,email, contact number and password. I need the name to have a value, the email to have the correct format,contact number should be numbers at least 10 numbers and the password to be at least 6 characters.
try this
vUsername = etUsername.getText().toString();
vFirstname = etFirstname.getText().toString();
vEmail = etEmail.getText().toString();
vPwd = etPwd.getText().toString();
vCpwd = etCpwd.getText().toString();
if("".equalsIgnoreCase(vUsername) //vUsername.equalsIgnoreCase("") could lead to NPE
|| "".equalsIgnoreCase(vFirstname)
|| "".equalsIgnoreCase(vEmail)
|| "".equalsIgnoreCase(vPwd)
|| "".equalsIgnoreCase(vCpwd) )
{
Toast.makeText(userRegistration.this, "All Fields Required.",
Toast.LENGTH_SHORT).show();
}
checkemail(vEmail);
if(emailcheck==true)
{
// your code here
}
public void checkemail(String email)
{
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher matcher = pattern.matcher(email);
emailcheck = matcher.matches();
}
Alternatively, you can use a validation library to perform your validations on Android. It is driven by annotation and thereby it reduces a lot of boiler-plate code. Your use case when solved using this app would look like the following:
#Required(order = 1)
#Email(order = 2)
private EditText emailEditText;
#Password(order = 3)
#TextRule(order = 4, minLength = 6, message = "Enter at least 6 characters.")
private EditText passwordEditText;
#ConfirmPassword(order = 5)
private EditText confirmPasswordEditText;
#Checked(order = 6, message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;
There is a dearth of documentation now but the annotation example on the home page should get you started. You can also read this blog on how to create custom rules in case the stock rules do not fit your needs.
PS: I am the author of this library.
You can use the default Android validation API.
Here is a very simple tutorial: http://blog.donnfelker.com/2011/11/23/android-validation-with-edittext/
The key is to use the setError method on your EditText. It will trigger default validation UI with provided error text.
for validation of edittext, use android:inputtype, android:maxLength.
Apart from this, can use regex for validation of form
You have two possibilities:
listen to changes to the field's content and run validation of that specific field or
listen to the submit-button click and validate the content of all fields on submit.
Else validation is just the same as in every other Java app: just test your constraints.
BTW: your question was already answered on stackoverflow.
try this
if(phone.getText().toString().isEmpty()){
if(phone.lenth <= 10){
}else{ // phone is`t correct }
phone.setError("phone number is empty ");
phone.requestFocus();
return;
}
if(password.getText().toString().isEmpty()){
if(password.lenth <= 6){
}else{ // password is`t correct }
password.setError("password number is empty ");
password.requestFocus();
return;
}

validating EditText input

Trying to confirm that an EditText tool is not empty when the user clicks a button. Whenever the EditText is not blank the code works. But whenever it is blank my program crashes. Any ideas what I'm doing wrong? Thanks.
if (et1.getText().toString() != null) {
inpt_weight = Integer.parseInt(et1.getText().toString());
Toast.makeText(getBaseContext(), "weight is not null", Toast.LENGTH_LONG).show();
} else {
inpt_weight = 0;
Toast.makeText(getBaseContext(), "weight is null", Toast.LENGTH_LONG).show();
};
I think its trying to parse an empty string("") to an integer which is not possible
try:
if (!et1.getText().toString().equalsIgnoreCase("") && et1.getText().toString() != null)
This will be a good way:
if(et1.getText().toString().trim().length()==0){
Log.d("No data","No text found in the edit text");
}
This also checks if the user had put nothing but only spaces.
In your code, I see you're converting the text to numbers.
In this case, either put correct IMEMethod for the edit text so that it takes only numbers, or check in your code that user has entered only numeric characters, else you'll end up with a NumberFormatException while conversion if the user has entered non numeric characters.
Try the following code please..
if(et1.getText().toString().equals("")){
Toast.makeText(getApplication(), "weight is null", Toast.LENGTH_SHORT).show();}
else{
inpt_weight = Integer.parseInt(et1.getText().toString());
Toast.makeText(getApplication(), "weight is not null & it is : "+inpt_weight,Toast.LENGTH_SHORT).show();
}

Categories

Resources