Check a string is contain "+" sign and number only - android

I have a String and sometimes value changed:
String str1 = "+25"; // only have "+" sign and number
String str2 = "+Name"; // only have "+" sign and text
How can I distinguish these String because I want to do something like that:
if (isString1Type) { // both strings also have "+" sign
// do something
}
Do String have any functions for this case.
Can anyone give me suggestions?

Yes, you could do something like this:
String str = "+Name";
boolean hasPlusSign = str.contains("+");
boolean isNumber = tryParseInt(str.replace("+", ""));
if(hasPlusSign && isNumber){ //if the string is +25 for example here will be true, else it will go to the else statement
//do something
} else {
//something else
}
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}

You can use the simple regex "[+][0-9]+". It more simple and easy.
Here is example code
String str1 = "+25";
if (str1.matches("[+][0-9]+")){
// your string contains plus "+" and number
// do something
}eles{
}
Hope this help

You can use regex like this:
[0-9]+ here + means more than one digits from 0-9
String str1 = "+25";
String str2 = "+Name";
String regex = "[0-9]+";
if(isDigit(str1.replace("+",""))){
Log.d("str1","Integer");
}else{
Log.d("str1","Not Integer");
}
if(isDigit(str2.replace("+",""))){
Log.d("str2","Integer");
}else{
Log.d("str2","Not Integer");
}
boolean isDigit(String str){
if(str.matches(regex)){
return true;
}else {
return false;
}
}

Related

Contact Validation in android

In this I am trying to validate phone number . but even if i do enter correct number it wont verify. code is below
cont=(EditText)findViewById(R.id.editcontact);
final String MobilePattern = "[0-9]{10}";
btn_log=(Button)findViewById(R.id.button_log);
btn_log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String phn=cont.getText().toString();
if (!phn.matches(MobilePattern)) {
Toast.makeText(LoginActivity.this, "Invalid Contact number", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
}
});
your regex is proper but you are using it in incorrect way, you need to compile your pattern before using it to match.
String patterntomatch ="[0-9]{10}";
Pattern pattern=Pattern.compile(patterntomatch);
Matcher matcher=pattern.matcher(phn);
if (!matcher.find()) {
Toast.makeText(LoginActivity.this, "Invalid Contact number", Toast.LENGTH_SHORT).show();
} else {
//To get matching text you can use
String ans = phn.substring(matcher.start(), matcher.end());
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
first try
final String phn=cont.getText().toString().trim();
it will help you when your content contains any spaces.
try by changing below things
final String MobilePattern = "[0-9]";
.......
final String phn=cont.getText().toString().trim();
.........
if (!phn.matches(MobilePattern) || phn.length() != 10 ) {
Toast.makeText(LoginActivity.this, "Invalid Contact number", Toast.LENGTH_SHORT).show();
}
Here I am giving you two step simple solution, At the very first allow user only take the valid input.
So use in your XML.
android:digits="0123456789"
android:inputType="phone"
android:maxLength="10"
Hopefully you can easily can understand each line meaning. Secondly you can validate on button click like below is given.
tv_login.setOnClickListener(v -> {
if (!isValidMobile(etPhone.getText().toString())){
//Invalid Mobile Number
}else {
//Valid Mobile Number
}
});
private boolean isValidMobile(String phone) {
boolean check = false;
if (!Pattern.matches("[a-zA-Z]+", phone)) {
if (phone.length() < 10 || phone.length() > 10) {
check = false;
} else {
check = true;
}
} else {
check = false;
}
return check;
}

How I can use method to validate mobile numbers { 011xxxxxxxx and012xxxxxxxxand010xxxxxxxx}

String MobilePattern = "[0-9]{10}";
if (mobile_number.length() != 11 &&
!mobile_number.getText().toString().matches(MobilePattern) ) {
mobile_number.setError("Please Enter correct mobile number");
return;
}
how I can use method to validate mobile numbers { 011xxxxxxxx and 012xxxxxxxx and 010xxxxxxxx}
Try this with PhoneNumberUtil class:
package com.google.i18n.phonenumbers;
public static boolean isNumberValid(String countryCode, String phNumber) {
if (TextUtils.isEmpty(countryCode)) {// Country code could not be empty
return false;
}
if (phNumber.length() < 6) { // Phone number should be at least 6 digits
return false;
}
boolean resultPattern = Patterns.PHONE.matcher(phNumber).matches();
if (!resultPattern) {
return false;
}
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(countryCode));
Phonenumber.PhoneNumber phoneNumber = null;
try {
phoneNumber = phoneNumberUtil.parse(phNumber, isoCode);
} catch (NumberParseException e) {
return false;
}
return phoneNumberUtil.isValidNumber(phoneNumber);
}
Where countryCode is the dialcode of a country : 33 for France , 34 for Spain etc...
You can check if number start with values you need or no, ex :
String mob = mobile_number.getText().toString();
if(mob.startsWith("010") || mob.startsWith("011") || mob.startWith("012")){
//todo your logic here
}

How to compare strings in my case (android)

I have two string that i get them with this code
final String encrypted_id = encryption.encryptOrNull(android_id);
final String preLoad = preferences.getString("pur", "no");
for make sure that they are equal i Log them like this
Log.d("encrypted_id",encrypted_id);
Log.d("preferences.getString",preferences.getString("pur", "no"));
and LogCat output is like this
D/encrypted_id﹕ wxgNDxqzNWNgYWrE0fxjaU07a54XBFnAToy56MAV1Y0=
D/preferences.getString﹕ wxgNDxqzNWNgYWrE0fxjaU07a54XBFnAToy56MAV1Y0=
so I make sure that they are equal
NOW i want to compare them like this
if(preLoad.equals(encrypted_id))
{
Log.d("app","is premium");
}
else {
Log.d("app","is not premium");
}
BUT LogCat show this to me
D/app﹕ is not premium
What's the problem ?
PS: I tried
1 . preLoad.equalsIgnoreCase(encrypted_id)
2 . preLoad.compareTo(encrypted_id)==0
change:
if(preLoad.equals(encrypted_id))
{
Log.d("app","is premium");
}
else {
Log.d("app","is not premium");
}
to
if(preLoad.trim().equals(encrypted_id.trim()))
{
Log.d("app","is premium");
}
else {
Log.d("app","is not premium");
}
You can try this:
if(stringsCompare(preLoad.trim(),encrypted_id.trim()))
{
Log.d("app","is premium");
}
else {
Log.d("app","is not premium");
}
stringsCompare is a procedure that I wrote for string comparison:
public boolean stringsCompare(String firstString, String secondString){
if(firstString.length() != secondString.length()){
//The length of the two strings are not equal
return false;
}else{
for(int i = 0; i < firstString.length(); i++)
{
if (firstString.charAt(i) != secondString.charAt(i))
{
//Let's log the difference:
Log.d("app","Difference at char: "+i+" its value in the first string is: "+firstString.charAt(i)+" and its value in the first string is: "+secondString.charAt(i));
//The strings are not equal
return false;
}
}
//All characters were equal
return true;
}
}
In this case you can see the difference if there is any.
Try this,
if(!preLoad.trim().equals(encrypted_id.trim()))
{
Log.d("app","is not premium");
}
else {
Log.d("app","is premium");
}

Email and phone Number Validation in android

I have a registration form in my application which I am trying to validate. I'm facing some problems with my validation while validating the phone number and email fields.
Here is my code:
private boolean validate() {
String MobilePattern = "[0-9]{10}";
//String email1 = email.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (name.length() > 25) {
Toast.makeText(getApplicationContext(), "pls enter less the 25 character in user name", Toast.LENGTH_SHORT).show();
return true;
} else if (name.length() == 0 || number.length() == 0 || email.length() ==
0 || subject.length() == 0 || message.length() == 0) {
Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
return false;
} else if (email.getText().toString().matches(emailPattern)) {
//Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
return true;
} else if(!email.getText().toString().matches(emailPattern)) {
Toast.makeText(getApplicationContext(),"Please Enter Valid Email Address",Toast.LENGTH_SHORT).show();
return false;
} else if(number.getText().toString().matches(MobilePattern)) {
Toast.makeText(getApplicationContext(), "phone number is valid", Toast.LENGTH_SHORT).show();
return true;
} else if(!number.getText().toString().matches(MobilePattern)) {
Toast.makeText(getApplicationContext(), "Please enter valid 10 digit phone number", Toast.LENGTH_SHORT).show();
return false;
}
return false;
}
I have used this code above for the validation. The problem I'm facing is in the phone number and email validation, only one validation is working. For example, if I comment out the phone number validation, the email validation is working properly. If I comment out the email validation, the phone number validation is working. If use both validations, it's not working.
For Email Address Validation
private boolean isValidMail(String email) {
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
return Pattern.compile(EMAIL_STRING).matcher(email).matches();
}
OR
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
For Mobile Validation
For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number. If your main target is your own country then you can match with the length. Assuming India has 10 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 two Function:
private boolean isValidMobile(String phone) {
if(!Pattern.matches("[a-zA-Z]+", phone)) {
return phone.length() > 6 && phone.length() <= 13;
}
return false;
}
OR
private boolean isValidMobile(String phone) {
return android.util.Patterns.PHONE.matcher(phone).matches();
}
Use Pattern package in Android to match the input validation for email and phone
Do like
android.util.Patterns.EMAIL_ADDRESS.matcher(input).matches();
android.util.Patterns.PHONE.matcher(input).matches();
Android has build-in patterns for email, phone number, etc, that you can use if you are building for Android API level 8 and above.
private boolean isValidEmail(CharSequence email) {
if (!TextUtils.isEmpty(email)) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
return false;
}
private boolean isValidPhoneNumber(CharSequence phoneNumber) {
if (!TextUtils.isEmpty(phoneNumber)) {
return Patterns.PHONE.matcher(phoneNumber).matches();
}
return false;
}
Try this
public class Validation {
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public static final boolean isValidPhoneNumber(CharSequence target) {
if (target.length()!=10) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
}
He want an elegant and proper solution try this small regex pattern matcher.
This is specifically for India.(First digit can't be zero and and then can be any 9 digits)
return mobile.matches("[1-9][0-9]{9}");
Pattern Breakdown:-
[1-9] matches first digit and checks if number(integer) lies between(inclusive) 1 to 9
[0-9]{9} matches the same thing but {9} tells the pattern that it has to check for upcoming all 9 digits.
Now the {9} part may vary for different countries so you may have array which tells the number of digits allowed in phone number. Some countries also have significance for zero ahead of number, so you may have exception for those and design a separate regex patterns for those countries phone numbers.
in Kotlin you can use Extension function to validate input
// for Email validation
fun String.isValidEmail(): Boolean =
this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()
// for Phone validation
fun String.isValidMobile(phone: String): Boolean {
return Patterns.PHONE.matcher(phone).matches()
}
try this:
extMobileNo.addTextChangedListener(new MyTextWatcher(extMobileNo));
private boolean validateMobile() {
String mobile =extMobileNo.getText().toString().trim();
if(mobile.isEmpty()||!isValidMobile(mobile)||extMobileNo.getText().toString().toString().length()<10 || mobile.length()>13 )
{
inputLayoutMobile.setError(getString(R.string.err_msg_mobile));
requestFocus(extMobileNo);
return false;
}
else {
inputLayoutMobile.setErrorEnabled(false);
}
return true;
}
private static boolean isValidMobile(String mobile)
{
return !TextUtils.isEmpty(mobile)&& Patterns.PHONE.matcher(mobile).matches();
}
The built in PHONE pattern matcher does not work in all cases.
So far, this is the best solution I have found to validate a phone number (code in Kotlin, extension of String)
fun String.isValidPhoneNumber() : Boolean {
val patterns = "^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$"
return Pattern.compile(patterns).matcher(this).matches()
}
//validation class
public class EditTextValidation {
public static boolean isValidText(CharSequence target) {
return target != null && target.length() != 0;
}
public static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public static boolean isValidPhoneNumber(CharSequence target) {
if (target.length() != 10) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
//activity or fragment
val userName = registerNameET.text?.trim().toString()
val mobileNo = registerMobileET.text?.trim().toString()
val emailID = registerEmailIDET.text?.trim().toString()
when {
!EditTextValidation.isValidText(userName) -> registerNameET.error = "Please provide name"
!EditTextValidation.isValidEmail(emailID) -> registerEmailIDET.error =
"Please provide email"
!EditTextValidation.isValidPhoneNumber(mobileNo) -> registerMobileET.error =
"Please provide mobile number"
else -> {
showToast("Hello World")
}
}
**Hope it will work for you... It is a working example.
I am always using this methode for Email Validation:
public boolean checkForEmail(Context c, EditText edit) {
String str = edit.getText().toString();
if (android.util.Patterns.EMAIL_ADDRESS.matcher(str).matches()) {
return true;
}
Toast.makeText(c, "Email is not valid...", Toast.LENGTH_LONG).show();
return false;
}
public boolean checkForEmail() {
Context c;
EditText mEtEmail=(EditText)findViewById(R.id.etEmail);
String mStrEmail = mEtEmail.getText().toString();
if (android.util.Patterns.EMAIL_ADDRESS.matcher(mStrEmail).matches()) {
return true;
}
Toast.makeText(this,"Email is not valid", Toast.LENGTH_LONG).show();
return false;
}
public boolean checkForMobile() {
Context c;
EditText mEtMobile=(EditText)findViewById(R.id.etMobile);
String mStrMobile = mEtMobile.getText().toString();
if (android.util.Patterns.PHONE.matcher(mStrMobile).matches()) {
return true;
}
Toast.makeText(this,"Phone No is not valid", Toast.LENGTH_LONG).show();
return false;
}
For check email and phone number you need to do that
public static boolean isValidMobile(String phone) {
boolean check = false;
if (!Pattern.matches("[a-zA-Z]+", phone)) {
if (phone.length() < 9 || phone.length() > 13) {
// if(phone.length() != 10) {
check = false;
// txtPhone.setError("Not Valid Number");
} else {
check = android.util.Patterns.PHONE.matcher(phone).matches();
}
} else {
check = false;
}
return check;
}
public static boolean isEmailValid(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();
return check;
}
String enter_mob_or_email="";//1234567890 or test#gmail.com
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid
}else isEmailValid(enter_mob_or_email){//Email is valid
}else{// Not valid email or phone number
}
XML
<android.support.v7.widget.AppCompatEditText
android:id="#+id/et_email_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:hint="Enter Email or Phone Number"/>
Java
private AppCompatEditText et_email_contact;
private boolean validEmail = false, validPhone = false;
et_email_contact = findViewById(R.id.et_email_contact);
et_email_contact.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) {
String regex = "^[+]?[0-9]{10,13}$";
String emailContact = s.toString();
if (TextUtils.isEmpty(emailContact)) {
Log.e("Validation", "Enter Mobile No or Email");
} else {
if (emailContact.matches(regex)) {
Log.e("Validation", "Valid Mobile No");
validPhone = true;
validEmail = false;
} else if (Patterns.EMAIL_ADDRESS.matcher(emailContact).matches()) {
Log.e("Validation", "Valid Email Address");
validPhone = false;
validEmail = true;
} else {
validPhone = false;
validEmail = false;
Log.e("Validation", "Invalid Mobile No or Email");
}
}
}
});
if (validPhone || validEmail) {
Toast.makeText(this, "Valid Email or Phone no", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "InValid Email or Phone no", Toast.LENGTH_SHORT).show();
}
private fun isValidMobileNumber(s: String): Boolean {
// 1) Begins with 0 or 91
// 2) Then contains 6 or 7 or 8 or 9.
// 3) Then contains 9 digits
val p: Pattern = Pattern.compile("(0|91)?[6-9][0-9]{9}")
// Pattern class contains matcher() method
// to find matching between given number
val m: Matcher = p.matcher(s)
return m.find() && m.group().equals(s)
}

Checking if string is web address or ip on android

I need to validate if string entered in TextEdit is a web address eg. "www.stackoverflow.com" or an ip address eg. "64.34.119.12". I have tried this two methods without success. I have private class variable named ip.
Method 1:
public boolean isAdress(){
boolean isaddr = true;
try
{
ip = new NetTask().execute(""+textEdit1.getText()).get();
}
catch (Exception ex)
{
isaddr = false;
}
return isaddr;
}
Method 2 is the one were I check string before sending it to NetTask.
public boolean isAdress(){
String adress = textEdit1.getText().toString();
boolean isaddr = true;
if (adress.length() > 0) {
String[] nums = adress.split(".");
if (nums.length == 4) {
for (String str : nums) {
int i = Integer.parseInt(str);
if ((i < 0) || (i > 255)) {
isaddr = false;
}
}
}
}
return isaddr;
}
this second method also doesn't wotk, but even if it did, it wouldn't be able to validate web adress.
So it there any way I can validate string for both of this cases?
EDIT:
After reading about regex I tried this method also:
private String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
public boolean isAdress(){
String adress = textEdit1.getText().toString();
try {
Pattern patt = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = patt.matcher(adress);
return matcher.matches();
} catch (RuntimeException e) {
return false;
}
}
but it seems to return false all the time.
Short answer: Try using regex!
EDIT:
if(textEdit1.getText().matches(REGEX_URL)) {
//DO URL THINGS
}
if(textEdit1.getText().matches(REGEX_IPADDRES)) {
//DO IP THINGS
}
If you google you can find the correct REGEX strings for IP addresses and urls...
NOTE:
A regex for urls can be different for what you want, do you only want http:// https:// or all valid urls (like market://)...
Patterns.IP_ADDRESS.matcher(url).matches();
Validation of IP Address in Kotlin which returns true or false
fun isValidIPAddress(ip:String):Boolean {
val reg0To255 = ("(\\d{1,2}|(0|1)\\" + "d{2}|2[0-4]\\d|25[0-5])").toRegex()
return reg0To255.matches(ip)
}
val inputIP = "127.1.1.775"
println("Input: " + inputIP)
println("Output: " + isValidIPAddress(inputIP))
Input: 127.1.1.775
Output: false
how about simpler approach? detect if it is IP address, e.g.
public static boolean isIP(String input) {
if (input.contains(".") && input.length()>1) {
return TextUtils.isDigitsOnly( input.replace(".", "").trim() );
}
else {
return false;
}
}

Categories

Resources