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.
Related
In my Flutter mobile app, I am trying to validate a phone number using regex. Below are the conditions.
Phone numbers must contain 10 digits.
In case country code us used, it can be 12 digits. (example country codes: +12, 012)
No space or no characters allowed between digits
In simple terms, here is are the only "valid" phone numbers
0776233475, +94776233475, 094776233475
Below is what I tried, but it do not work.
String _phoneNumberValidator(String value) {
Pattern pattern =
r'/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/';
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(value))
return 'Enter Valid Phone Number';
else
return null;
}
How can I solve this?
You could make the first part optional matching either a + or 0 followed by a 9. Then match 10 digits:
^(?:[+0]9)?[0-9]{10}$
^ Start of string
(?:[+0]9)? Optionally match a + or 0 followed by 9
[0-9]{10} Match 10 digits
$ End of string
Regex demo
Validation using Regex:
String validateMobile(String value) {
String pattern = r'(^(?:[+0]9)?[0-9]{10,12}$)';
RegExp regExp = new RegExp(pattern);
if (value.length == 0) {
return 'Please enter mobile number';
}
else if (!regExp.hasMatch(value)) {
return 'Please enter valid mobile number';
}
return null;
}
#override
String validator(String value) {
if (value.isEmpty) {
return 'Mobile can\'t be empty';
} else if (value.isNotEmpty) {
//bool mobileValid = RegExp(r"^(?:\+88||01)?(?:\d{10}|\d{13})$").hasMatch(value);
bool mobileValid =
RegExp(r'^(?:\+?88|0088)?01[13-9]\d{8}$').hasMatch(value);
return mobileValid ? null : "Invalid mobile";
}
}
I used the RegExp provided by #Dharmesh
This is how you can do it with null safety.
bool isPhoneNoValid(String? phoneNo) {
if (phoneNo == null) return false;
final regExp = RegExp(r'(^(?:[+0]9)?[0-9]{10,12}$)');
return regExp.hasMatch(phoneNo);
}
Usage:
bool isValid = isPhoneNoValid('your_phone_no');
String phoneNumberValidator(String value) {
Pattern pattern =
r'\+994\s+\([0-9]{2}\)\s+[0-9]{3}\s+[0-9]{2}\s+[0-9]{2}';
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(value))
return 'Enter Valid Phone Number';
else
return null;
}
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
}
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 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'm trying to make an if/else statement that if s1 is null, it will show files from an SD card, but if s1 is not null, it will show SD card file that contain user inputs. However, my code fails and never reaches the if/else statement:
EditText s1 = (EditText) findViewById(R.id.search1);
try
{
for (File ff : dirs)
{
//search.equals("")
if (s1.getText().toString().equals(""))//if null
{
if (ff.isDirectory())
dir.add(new Option(ff.getName(), "Folder", ff.getAbsolutePath()));
else
{
fls.add(new Option(ff.getName(), "File Size: " + ff.length(), ff.getAbsolutePath()));
}
}
else
{
if (ff.getName().contains(s1.toString()))//show file search
{
if(ff.isDirectory())
dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath()));
else
{
fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
}
}
}
//Toast.makeText(this, (CharSequence) s1, Toast.LENGTH_SHORT).show();
}
}
Try this:
if (s1.getText().toString()==null){
....
It's hard to know what your question really is but I suspect that this:
if (ff.getName().contains(s1.toString()))
Isn't what you think it is. What are you expecting to get from s1.toString()? It's not going to be the value of the EditText entry and it's not going to be the english looking ID that you gave it in the XML. It's going to be whatever internal java label is associated with this input, is that really what your file names are? if not then this match will always fail.
use this code..
if( edit_text.getText().toString().trim().equals(""))