Checking if string is web address or ip on android - 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;
}
}

Related

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 use regex for detecting correct pattern of email address in android

I am making a user login application in android.In register section for using correct pattern of email address i am using regex expression.It is working fine but main problem is that i can login as xyz#123.com but i want only (gmail,hotmail,yahoo & rediffmail) not 123 or abc etc.How can i do this.My code is
public static boolean isEmailValid(String email,EditText et) {
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;
}else{
et.setError(Html.fromHtml("<font color='#000'>Plese type valid Email Address</font>"));
}
return isValid;
}
plz help me.
Use predefined EMAIL_ADDRESS pattern in in https://developer.android.com/reference/android/util/Patterns.html.
I think it's better to let the validation decoupled from any logic (error display, views etc...) :
Create an interface : ValidationCallback.java
public interface ValidationCallback {
void onEval (boolean isValid);
}
Then a Utility class where all your validation rules will go (isNumeric is....) : Lang.java
public class Lang {
private final static Set<String> Providers;
static {
Providers = new HashSet<String> ();
Providers.add ("gmail");
Providers.add ("yahoo");
Providers.add ("outlook");
}
public static void checkEmailValidity (String input, ValidationCallback callback) {
if (callback != null) {
callback.onEval (isEmailValid (input));
}
}
public static boolean isEmailValid (String input) {
String emailExp = "[a-zA-Z0-9][a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{0,255}\\#[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+";
Pattern pattern = Pattern.compile (emailExp);
boolean isValid = pattern.matcher (input).matches ();
if (isValid) {
String provider = input.split ("#")[1].split (".")[0].toLowerCase ();
if (!Providers.contains (provider)) {
isValid = false;
}
}
return isValid;
}
}
Then from your Activity or another Utility class that has the view :
ValidationCallback callback = new ValidationCallback () {
#Override
public void onEval (boolean isValid) {
if (!isValid) {
editText.setError(Html.fromHtml("<font color='#000'>Plese type valid Email Address</font>"));
}
}
}
Lang.checkEmailValidity (editText.getText (), callback);
Or if you don't want to use the callback mechanism :
if (!Lang.isEmailValid (editText.getText ())) {
editText.setError(Html.fromHtml("<font color='#000'>Plese type valid Email Address</font>"));
}
You get the picture, you can tweak it however you want.

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

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;
}
}

Settings Non-English language password on android phone?

With Reference to this question on android stack, i have a solution to do which allows android phone to provide support for setting non-english language password.
My phones SRC is based on stock-android which is not allowing me to set password which is non-ascii standards like Hebrew.
Based from AOSP source code that handles the password input for lock screen, ChooseLockPassword.java, inside validatePassword() (line 292), here is a snippet that will show the "illegal character" message (from line 311):
// allow non control Latin-1 characters only
if (c < 32 || c > 127) {
return getString(R.string.lockpassword_illegal_character);
}
I have commented out this part but i don't think so this will work. [Waiting to be Flashed]
There are no such question for this condition, i need help for cracking the possibility for doing this any "Work around" will also do.
So after fighting few days i got a workaround by implementing my method for it.
private String validateHebrewPassword(String password)
{
if (password.length() < mPasswordMinLength) {
return getString(mIsAlphaMode ?
R.string.lockpassword_password_too_short
: R.string.lockpassword_pin_too_short, mPasswordMinLength);
}
if (password.length() > mPasswordMaxLength) {
return getString(mIsAlphaMode ?
R.string.lockpassword_password_too_long
: R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1);
}
for (int i = 0; i < password.length(); i++)
{
char c = password.charAt(i);
System.out.println("Validate Hebrew Password Success "+ " Char "+c+" for password "+password+ " langauage "+locale);
}
return null;
}
And modiying its validatePasswor() caller a bit specific to hebrew like:
private void handleNext() {
final String pin = mPasswordEntry.getText().toString();
if (TextUtils.isEmpty(pin)) {
return;
}
String errorMsg = null;
if (mUiStage == Stage.Introduction)
{
String locale = java.util.Locale.getDefault().getLanguage();
if(locale.equals("iw")) //Specific Hebrew check
{
errorMsg = validateHebrewPassword(pin); //New Method
}
else
{
errorMsg = validatePassword(pin); //AOSP Method
}
if (errorMsg == null)
{
mFirstPin = pin;
mPasswordEntry.setText("");
updateStage(Stage.NeedToConfirm);
}
} else if (mUiStage == Stage.NeedToConfirm) {
if (mFirstPin.equals(pin)) {
final boolean isFallback = getActivity().getIntent().getBooleanExtra(
LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false);
mLockPatternUtils.clearLock(isFallback);
mLockPatternUtils.saveLockPassword(pin, mRequestedQuality, isFallback);
getActivity().setResult(RESULT_FINISHED);
getActivity().finish();
} else {
CharSequence tmp = mPasswordEntry.getText();
if (tmp != null) {
Selection.setSelection((Spannable) tmp, 0, tmp.length());
}
updateStage(Stage.ConfirmWrong);
}
}
if (errorMsg != null) {
showError(errorMsg, mUiStage);
}
}
private void updateUi() {
String password = mPasswordEntry.getText().toString();
final int length = password.length();
if (mUiStage == Stage.Introduction && length > 0) {
if (length < mPasswordMinLength) {
String msg = getString(mIsAlphaMode ? R.string.lockpassword_password_too_short
: R.string.lockpassword_pin_too_short, mPasswordMinLength);
mHeaderText.setText(msg);
mNextButton.setEnabled(false);
} else
{
String locale = java.util.Locale.getDefault().getLanguage();
String error = null;
if(locale.equals("iw")) //Specific Hebrew check
{
error = validateHebrewPassword(password); //New method
}
else
{
error = validatePassword(password); //AOSP Method
}
if (error != null) {
mHeaderText.setText(error);
mNextButton.setEnabled(false);
} else {
mHeaderText.setText(R.string.lockpassword_press_continue);
mNextButton.setEnabled(true);
}
}
} else {
mHeaderText.setText(mIsAlphaMode ? mUiStage.alphaHint : mUiStage.numericHint);
mNextButton.setEnabled(length > 0);
}
mNextButton.setText(mUiStage.buttonText);
}

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)
}

Categories

Resources