Regular Expression In Android for Password Field - android

How can i validating the EditText with Regex by allowing particular characters .
My condition is :
Password Rule:
One capital letter
One number
One symbol (#,$,%,&,#,) whatever normal symbols that are acceptable.
May I know what is the correct way to achieve my objective?

Try this may helps
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$
How it works?
^ # start-of-string
(?=.*[0-9]) # a digit must occur at least once
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.*[##$%^&+=]) # a special character must occur at least once you can replace with your special characters
(?=\\S+$) # no whitespace allowed in the entire string
.{4,} # anything, at least six places though
$ # end-of-string
How to Implement?
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.edtText);
Button btnCheck = (Button) findViewById(R.id.btnCheck);
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (isValidPassword(editText.getText().toString().trim())) {
Toast.makeText(MainActivity.this, "Valid", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "InValid", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean isValidPassword(final String password) {
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$";
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
}

And for the Kotlin lovers :
fun isValidPassword(password: String?) : Boolean {
password?.let {
val passwordPattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$"
val passwordMatcher = Regex(passwordPattern)
return passwordMatcher.find(password) != null
} ?: return false
}

None of the above worked for me.
What worked for me:
fun isValidPasswordFormat(password: String): Boolean {
val passwordREGEX = Pattern.compile("^" +
"(?=.*[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 spaces
".{8,}" + //at least 8 characters
"$");
return passwordREGEX.matcher(password).matches()
}
Source: Coding in Flow
Hope it helps someone.

Try this.
(/^(?=.*\d)(?=.*[A-Z])([#$%&#])[0-9a-zA-Z]{4,}$/)
(/^
(?=.*\d) //should contain at least one digit
(?=.*[#$%&#]) //should contain at least one special char
(?=.*[A-Z]) //should contain at least one upper case
[a-zA-Z0-9]{4,} //should contain at least 8 from the mentioned characters
$/)

try {
if (subjectString.matches("^(?=.*[#$%&#_()=+?»«<>£§€{}\\[\\]-])(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).*(?<=.{4,})$")) {
// String matched entirely
} else {
// Match attempt failed
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
(?=.*[#\$%&#_()=+?»«<>£§€{}.[\]-]) -> must have at least 1 special character
(?=.*[A-Z]) -> Must have at least 1 upper case letter
(?=.*[a-z]) -> Must have at least 1 lower case letter
(?=.*\\d) -> Must have at least 1 digit
(?<=.{4,})$") -> Must be equal or superior to 4 chars.

As an addition to the answers already given, I would suggest a different route for identifying special characters and also would split up the check for the different rules.
First splitting it up: Instead of making one big rule, split it and check every rule separately, so that you are able to provide feedback to the user as to what exactly is wrong with his password. This might take a bit longer but in something like a password checkup this will not be noticable. Also, this way the conditions are more readable.
Secondly, instead of checking for a list of special characters, you could flip it and check if the password contains any characters that are neither letters of the latin alphabet (a-zA-Z) nor digits (0-9). That way you don't "forget" special characters. For example, lets say you check specifically but in your check you forget a character like "{”. With this approach, this can't happen. You can extend that list by things you don't consider to be special characters explicitly, for example a space. In kotlin, it would look like this:
val errorText = when {
/* Rule 1 */
!password.contains(Regex("[A-Z]")) -> "Password must contain one capital letter"
/* Rule 2 */
!password.contains(Regex("[0-9]")) -> "Password must contain one digit"
/* Rule 3, not counting space as special character */
!password.contains(Regex("[^a-zA-Z0-9 ]")) -> "Password must contain one special character"
else -> null
}
Depending on your encoding, you can also use regex and define your special characters using ranges of hex codes like
Reges("[\x00-\x7F]")

I'm too late to answer but still it may help you.
I've worked with Kotlin.
Add following function.
private fun isValidPassword(password: String): Boolean {
val pattern: Pattern
val matcher: Matcher
val specialCharacters = "-#%\\[\\}+'!/#$^?:;,\\(\"\\)~`.*=&\\{>\\]<_"
val PASSWORD_REGEX = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[$specialCharacters])(?=\\S+$).{8,20}$"
pattern = Pattern.compile(PASSWORD_REGEX)
matcher = pattern.matcher(password)
return matcher.matches()
}
Function description:
(?=.*[0-9]) # a digit must occur at least once
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.[-#%[}+'!/#$^?:;,(")~`.=&{>]<_]) # a special character must occur at least once
replace with your special characters
(?=\S+$) # no whitespace allowed in the entire string .{8,} #
anything, at least six places though
You can modify it as needed.
Hope it helps.

you can use the class Patern than Matcher for every checking format.
I give you an exemple of use :
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher matcher = pattern.matcher(myEmailString);
if (!myEmailString.contains("#") || !matcher.matches()) {
// error in the email : do staff
myEmailView.setError("invalid email !");
}

All of the other answers are good, but the implementation of special characters were a bit too messy for my taste. I used Unicode for special characters instead.
I used special characters specified in the OWASP website.
Kotlin:
val SPECIAL_CHARACTERS_REGEX =
"?=.*[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]"
val PASSWORD_REGEX =
"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])($SPECIAL_CHARACTERS_REGEX).{8,}\$"
fun isValidPassword(password: String) = Pattern.matches(PASSWORD_REGEX, password)

Most common password validation is
At least 8 character
Require numbers
Require special character
Require uppercase letters
Require lowercase letters
Regex:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\/%§"&“|`´}{°><:.;#')(#_$"!?*=^-]).{8,}$
Kotlin code:
val PASSWORD_REGEX_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\/%§"&“|`´}{°><:.;#')(#_$"!?*=^-]).{8,}$"
fun isValidPassword(password: String?): Boolean {
val pattern: Pattern =
Pattern.compile(PASSWORD_REGEX_PATTERN)
val matcher: Matcher = pattern.matcher(password)
return matcher.matches()
}
online regex validator to check it:
https://regex101.com/
https://www.freeformatter.com/java-regex-tester.html#ad-output

private fun passwordValidate(password1: String, password2: String): Boolean {
when {
password1.length < 9 -> {
textView2.text = "Password Has To Be At Least 9 Characters Long"
return false
}
!password1.matches(".*[A-Z].*".toRegex()) -> {
textView2.text = "Password Must Contain 1 Upper-case Character"
return false
}
!password1.matches(".*[a-z].*".toRegex()) -> {
textView2.text = "Password Must Contain 1 Lower-case Character"
return false
}
!password1.matches(".*[!##$%^&*+=/?].*".toRegex()) -> {
textView2.text = "Password Must Contain 1 Symbol"
return false
}
password1 != password2 -> {
textView3.text = "Passwords Don't Match"
return false
}
else -> return true

Try this,
if (validatePassword())
{
// if valid
}
private boolean validatePassword() {
String passwordInput = password.getText().toString().trim();
if (!passwordInput.matches(".*[0-9].*")) {
Toast.makeText(mActivity, "Password should contain at least 1 digit", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches(".*[a-z].*")) {
Toast.makeText(mActivity, "Password should contain at least 1 lower case letter", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches(".*[A-Z].*")) {
Toast.makeText(mActivity, "Password should contain at least 1 upper case letter", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches(".*[a-zA-Z].*")) {
Toast.makeText(mActivity, "Password should contain a letter", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches( ".{8,}")) {
Toast.makeText(mActivity, "Password should contain 8 characters", Toast.LENGTH_SHORT).show();
return false;
}
else {
return true;
}
}

I have a simple way to check it without using regex in Kotlin.
It will check for password length >= 8, at least one capital letter, one small letter, one number, and one special character.
fun isValidPassword(pass:String):Boolean{
if(pass.length<8) return false
var u = 0
var l = 0
var d = 0
var s = 0
for (char in pass){
if(char.isUpperCase()) u++
else if(char.isLowerCase()) l++
else if(char.isDigit()) d++
else if(char in "##$%^&+=_.") s++
}
if(u==0|| l==0 || s==0 || d==0) return false
return true
}

Related

Starts comparing from the first number, not the whole number in kotlin

Hello I need to compare 2 numbers and I used >, => but it doesn't compare whole number, it looks for the leftest(left) number and compare
for example the number is 92,236 and i want to compare it with 100,000, it says 92236 is bigger than 100,000 and it is because of the first number which is 9 and the first number of second number that is 1 so it says 100,000 is not bigger than 9236
here what I had done
class IncreaseMoneyFragment : Fragment() {
var decide = ""
val increaseEditText = mIncreaseMoneyBinding.increaseEdt.text.toString() (get value of edit text)
val currentPayment = it.payment (get loanPayment from database)
if (increaseEditText > currentPayment) {
Toast.makeText(activity, "more", Toast.LENGTH_SHORT).show()
val more = "بیشتر"
decide = more
} else {
Toast.makeText(activity, "less", Toast.LENGTH_SHORT).show()
val less = "کمتر"
decide = less
}
builder.setTitle(" مبلغ مورد نظر از مبلغ قسط وام $decide است. ادامه میدهید؟")
THANKS FOR HELPING ME :)
You are most likely comparing strings (text) and not numbers here. That's why it's using the alphabetical order instead of the integer order:
println("92236" > "100000") // true
println(92236 > 100000) // false
You probably want to convert your strings into integers instead:
if (increaseEditText.toInt() > currentPayment.toInt()) {
// ...
}
Note that toInt will crash if the strings are not actual numbers (for instance empty).
You can use toIntOrNull if you want more safety. It returns null if the string is not a number, so you can simply check for null and deal with this problem separately before comparing.

Remove character from string in Kotlin

I am trying to create an Android calculator which uses strings in Kotlin. I do not know how to delete a comma (or the negative) if it already contains one.
Here is my code which adds the comma correctly but doesn't delete it if the user clicks again:
if (!buClickValue.contains(".")) {
buClickValue += "."
} else {
buClickValue.replace(".", "")
}
The replace() method is designed to return the value of the new String after replacing the characters. In your case, the value obtained after replacing the characters is never reassigned back to the original variable.
Specifically in your else clause, the line should be changed to -
buClickValue = buClickValue.replace(".", "")
The more logical technic is not to replace but to filter
buClickValue = buClickValue.filterNot { it == "."[0] }
or
buClickValue = buClickValue.filterNot { it == '.' }
Or to extend
filtered = ".,;:"
buClickValue = buClickValue.filterNot { filtered.indexOf(it) > -1 }

Password Patteren does not matched with the Matcher class

My Password should be Like :
"Password should contain at least one uppercase letter, one lowercase letter, one digit and one special character with minimum eight character length"
The Pattern I have used is : ^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$#$#!%*?&])[A-Za-z\\d$#$#!%*?&]{8,}
So, I have created a function as below in my Constant.java file :
public static Boolean passwordMatcher(TextInputLayout edtText,String string) {
Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)(?=.*[$#$#!%*?&])[A-Za-z\\\\d$#$#!%*?&]{8,}");
Matcher matcher = pattern.matcher(edtText.getEditText().getText().toString());
boolean isMatched = matcher.matches();
if (isMatched) {
return true;
}
if (!isMatched) {
edtText.setErrorEnabled(true);
edtText.setError("" + string);
edtText.setFocusable(true);
return false;
}
return true;
}
and in my MainActivity.java file I have checked for validation as below :
if (!Constant.passwordMatcher(edtPassword, mContext.getResources().getString(R.string.error_activity_signup_password_invalid))) {
return;
}
But, I am not getting success even if I have tried : 'Jaimin123#' as a my password.
Always getting error set in my TextInputLayout.
What might be the issue ?
Thanks.
Try using below regex for password match.
^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$
This regex will check for below rules:
At least one upper case letter
At least one lower case letter
At least one digit
At least one special character
Minimum 8 in length
Try this
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$##!%*?&]).{8,}$
If you don't want white space in password include (?=\S+$) also
Try this code:
public void checkPattern(String password) {
Pattern pattern = Pattern.compile("(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])(?=.*\\W).{8,}");
Matcher matcher = pattern.matcher(password);
boolean isMatched = matcher.matches();
System.out.println(isMatched);
}
Try
public boolean matchesPattern(String password) {
Pattern pattern = Pattern.compile("^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$");
Matcher matcher = pattern.matcher(password);
return matcher.matches();
}

How to restrict special characters and numbers in a searchView?

How can I allow only alphabetics (no special characters) in a search view control?
I tried following but it didn't work, it allows everything:
searchView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
(I don't want to use editbox where there is an option of setting the digits in a XML property itself.)
Docs: TextView.inputMethod
How can I make this work?
You can try something like this
EditText searchView= (EditText) findViewById(R.id.txtState);
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(searchView.getText().toString());
boolean bs = ms.matches();
if (bs == false) {
if (ErrorMessage.contains("invalid"))
ErrorMessage = ErrorMessage + "search,";
else
ErrorMessage = ErrorMessage + "invalid search,";
}
You may instead try:
searchView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
Or, you may set a check on the text entered. This function is a Kotlin extension function to check if a string contains only alphabets.
/**
*
* * Method to validate text for only alphabets
*/
fun String.isOnlyAlphabets(): Boolean {
return Pattern.compile("^[a-zA-Z ]+$").matcher(this).matches()
}

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}\$"

Categories

Resources