I am trying to validate password field for my application. I make validation to check whether string contain spaces or not but it's not accepting special character like '#' and others.
I need to allow user to enter special character but not allow to use white spaces.
Here is my validation code.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(oldPass);
Matcher matcher1 = pattern.matcher(newPass);
boolean found = matcher.find();
boolean found1 = matcher1.find();
if(found || found1)
{
DisplayError(Constants.PASSWORD_CANNOT_CONTAIN_SPACES);
}
Please give me any hint or reference.
update
if (newPass.indexOf(' ') != -1 || oldPass.indexOf(' ') != -1) {
DisplayError(Constants.PASSWORD_CANNOT_CONTAIN_SPACES);
}
I think it's too simple to use regular expressions.
if (password.indexOf(' ') != -1) {
// display error
}
Related
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();
}
In my application I have field name. It works perfect if field contain digits or .,?... characters but when I enter usman(space)shafi it gives error. My statement take space as invalid character between two words. Please can anyone tell me how to make it work. Thanks
here is the code
if(!Pattern.matches("[a-zA-Z]+", textname.getText().toString().trim())){
textname.setError("Invalid Characters");
}
// if(!Pattern.matches("[a-zA-Z]+", textkin.getText().toString().trim())){
// textkin.setError("Invalid Characters");
// }");
Add the space to your regular expresion:
if(!Pattern.matches("[a-zA-Z ]+", textname.getText().toString().trim())){
textname.setError("Invalid Characters");
}
If it would be just a one white space inside you can try something like this:
text = textname.getText().toString().trim();
string[] txtSplt = text.split(" ");
text = "";
foreach (string s : txtSplt)
{
text += s;
}
Then you can proceed with checking the condition without changing your regex.
DO this by this way. Your problem will be solved.
String regex = "([A-Z a-z]+)";
Pattern pattern1 = Pattern.compile(regex);
Matcher matcher1 = pattern1.matcher(textname.getText().toString());
if(!matcher1.matches()){
textname.setError("Invalid Characters");
}
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 want to use regex in my android application to validate some field.
User Name :
1 Capital Letter[A-Z], 2 digit[0-9], 1 Special Character any and then followed by small character[a-z] and lenth would be 10 character max.
Email Address :
Must contain #google.com in last
Mobile :
Must be +91 and after that 10 digit.
How can I form my regex pattern for all three fields..?
Regx for emailid:
^[A-Za-z][A-Za-z0-9]*([._-]?[A-Za-z0-9]+)#[A-Za-z].[A-Za-z]{0,3}?.[A-Za-z]{0,2}$
accepts values as:
hdf4.j8k#bfv.djf
ds.sd#c25v.fdv
dv_sdv#fvv
vdf-f#jn.fdv
jfk#mbf.khb.in
n etc
Regex for Mobile No:
^[7-9][0-9]{9}$
works perfect for indian mobile numbers.
Regex for landline No:
^[0-9]{3,5}-[2-9]{1}[0-9]{5,7}$
for landline numbers in india with region code
eg: 022-58974658
You can find the regex you require for password, email and more , for instance
For Username :
^[a-z0-9_-]{3,15}$
^ # Start of the line
[a-z0-9_-] # Match characters and symbols in the list, a-z, 0-9
, underscore , hyphen
{3,15} # Length at least 3 characters and maximum length of 15
$ # End of the line
at : http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/
Please see below link for Email Validation and you can modify some part of the code for username validation and phone number validation.
how-to-check-edittexts-text-is-email-address-or-not
public static boolean isEmailValid(String email) {
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;
}
return isValid;
}
Mobile :
Must be +91 and after that 10 digit.
^[7-9][0-9]{9}$ is useful for only mobile numbers. But for country code we should have to use regex like ^[+(00)][0-9]{6,14}$ ..
something like
1)
String phoneNumber = "+919900990000"
if(phoneNumber.matches("^[+(00)][0-9]{6,14}$")){
//True
2)
String phoneNumber = "9900990000"
if(phoneNumber.matches("^[+(00)][0-9]{6,14}$")){
//False
The first is true because it has the country code with it, But the second one is false because it has not any country code attached with it.
You can use Patterns class for validating factors such as email,mobile no etc.
Here's how:
public static boolean isValidEmail(CharSequence target) {
return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
}
public static boolean isValidMobile(CharSequence target) {
return (!TextUtils.isEmpty(target) && Patterns.PHONE.matcher(target).matches());
}
Hope it'll help you.
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;
}