I am new to android studio and kotlin. I need to find a way to check if a string contains a char, which is, in this case, "/"
I want to form a piece of code in the following manner:
if (string input contains a character "/") = true {
<code>
}
else{
<code>
}
Please tell me how to do this, and if possible, give me the code I'll need to specify as the condition.
You can use contains, like this:
val a = "hello/"
val b = a.contains("/")
When the string has the character will return true.
onSearchRequested() function only accept English character. For example when I put ş character in search box, it doesn't show me anything.
How can I define non-english characters into onSearchRequest?
Use pattern and matcher .. it would b better
see this As You Can Change pattern according to you ... by using symbols like [a-zA-Z0-9]
try this
EditText state = (EditText) findViewById(R.id.txtState);
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(state.getText().toString());
boolean bs = ms.matches();
if (bs == false) {
if (ErrorMessage.contains("invalid"))
ErrorMessage = ErrorMessage + "state,";
else
ErrorMessage = ErrorMessage + "invalid state,";
}
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
}
I have a EditText in android where IP Address is supposed to be entered. On click of a button I want to check if the text retrieved from EditText does :
not have any spaces
not have any letters
not empty
contain only numbers
and contain only periods "."
I have this if else condition to check if the user is allowed to go to the next activity but it still has some bugs. I don't know how to allow ONLY periods
if(((ip.length() != 0) || ip.contains(" ") == false || ip.matches("[a-z]+") == false) && (ip.matches("[0-9]+") && ip.contains(".")))
{
next = false;
}
else
{
next = true;
}
You can use this regex to check the input
"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
EDIT:
Do not use regex as things will break when IPv6 comes, use this instead
http://commons.apache.org/validator/apidocs/org/apache/commons/validator/routines/InetAddressValidator.html
Pretty simple with Regular Expression
private static final String PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
public static boolean validate(final String ip){
Pattern pattern = Pattern.compile(PATTERN);
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
}
I hope it will help you.
Thanks.
This will work:
<EditText
android:inputType="number"
android:digits="0123456789."
/>
allowing only numbers and .
You can do this much elegant by using android.util.Patterns:
import android.util.Patterns
...
boolean isIPvalid (String input) {
return Patterns.IP_ADDRESS.matcher(input).matches();
}
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;
}