Does Android have a function to validate passwords? - android

I'm developing an Android app and one of my tasks is to check the strength of a password.
Are there any built-in functions for checking the strength of a password?

In order to answer the question, there is no Android function to do this, the closest and best way is to use regex as Mkyong suggested on his blog:
private Pattern pattern;
private Matcher matcher;
private static final String PASSWORD_PATTERN =
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,20})";
public PasswordValidator(){
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/**
* Validate password with regular expression
* #param password password for validation
* #return true valid password, false invalid password
*/
public boolean validate(final String password){
matcher = pattern.matcher(password);
return matcher.matches();
}

If you dont't want to use external libs.. you can check it yourself.. Something like this:
public void onSubmitClicked(View v)
{
String pass = passwordEditText.getText().toString();
if(TextUtils.isEmpty(pass) || pass.length < [YOUR MIN LENGTH])
{
passwordEditText.setError("You must more characters in your password");
return;
}
if(....){
// do other controls here
}
}

Sounds like you need an external library such as http://code.google.com/p/vt-middleware/wiki/vtpassword etc.
Or it is simple enough to code up something like checking how long it is, what characters it has etc and printing out different things based on that.
If say a user had a 10 length password and some upper case characters you could increment some password strength parameter based on this, rewarding more complex passwords. You can set teh thresholds yourself.

Related

How can I set a specific email to use?

I want to create some code in my sign up activity which let people use only one email adress with a specific domain.
For example user on the registration form can use only email which domain is
: #ubu.com
otherwise people can not register with other email.
Thank you.
Assuming you want to validated the email domain in Client End only.
Use a regular expression. This expression validates any given string as email and checks if it's domain name matches .edu.com
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#" + "(edu\\.com)$"
Test method:
public boolean isEmailValid(String email) {
String regEx = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+ "(edu\\.com)$";
Pattern pattern = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
Now validate each email address before signing up.

How to validate an email address' specific domain?

I've seen solutions here to validate whether an email address is formatted correctly, however I would like to check if an email address uses a specific domain such as "#gmail.com". The example I am referring to which validates email address format in general is:
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
You might use endsWith and use #gmail.com like:
"test#gmail.com".endsWith("#gmail.com")
Or use a regex like ^\S+#gmail\.com$
Details
^ Assert position at the start of the line
\S+ Match any non whitespace characters one or more times
#gmail\.com match #gmail.com
$ Assert position at the end of the line
For example
if ("test#gmail.com".matches("^\\S+#gmail\\.com$")) {
System.out.println("Match!");
}
Demo Java
You could make use of regex.
Pattern p = Pattern.compile(".*#gmail\.com");
Matcher m = p.matcher("hello#gmail.com");
boolean b = m.matches();
The simplest solution would be checking if the email contains the specified domain. Later you could add a regex or even a dictionary to store the different domains, instead of using one method for each individual domain.
private boolean isFromGmailDomain(String email, String domain)
{
return email.contains(domain);
}
You could make use of regex.
You can check regex https://www.regextester.com/94044
^[a-zA-Z0-9_.+-]+#(?:(?:[a-zA-Z0-9-]+.)?[a-zA-Z]+.)?(domain.in|domain2.com)

Firestore - How to update a field that contains period(.) in it's key from Android?

Updating a field contains period (.) is not working as expected.
In docs, nested fields can be updated by providing dot-seperated filed path strings or by providing FieldPath objects.
So if I have a field and it's key is "com.example.android" how I can update this field (from Android)?
In my scenario I've to set the document if it's not exists otherwise update the document. So first set is creating filed contains periods like above and then trying update same field it's creating new field with nested fields because it contains periods.
db.collection(id).document(uid).update(pkg, score)
What you want to do is possible:
FieldPath field = FieldPath.of("com.example.android");
db.collection(collection).document(id).update(field, value);
This is happening because the . (dot) symbol is used as a separator between objects that exist within Cloud Firestore documents. That's why you have this behaviour. To solve this, please avoid using the . symbol inside the key of the object. So in order to solve this, you need to change the way you are setting that key. So please change the following key:
com.example.android
with
com_example_android
And you'll be able to update your property without any issue. This can be done in a very simple way, by encoding the key when you are adding data to the database. So please use the following method to encode the key:
private String encodeKey(String key) {
return key.replace(".", "_");
}
And this method, to decode the key:
private String decodeKey(String key) {
return key.replace("_", ".");
}
Edit:
Acording to your comment, if you have a key that looks like this:
com.social.game_1
This case can be solved in a very simple way, by encoding/decoding the key twice. First econde the _ to #, second encode . to _. When decoding, first decode _ to . and second, decode # to _. Let's take a very simple example:
String s = "com.social.game_1";
String s1 = encodeKeyOne(s);
String s2 = encodeKeyTwo(s1);
System.out.println(s2);
String s3 = decodeKeyOne(s2);
String s4 = decodeKeyTwo(s3);
System.out.println(s4);
Here are the corresponding methods:
private static String encodeKeyOne(String key) {
return key.replace("_", "#");
}
private static String encodeKeyTwo(String key) {
return key.replace(".", "_");
}
private static String decodeKeyOne(String key) {
return key.replace("_", ".");
}
private static String decodeKeyTwo(String key) {
return key.replace("#", "_");
}
The output will be:
com_social_game#1
com.social.game_1 //The exact same String as the initial one
But note, this is only an example, you can encode/decode this key according to the use-case of your app. This a very common practice when it comes to encoding/decoding strings.
Best way to overcome this behavior is to use the set method with a merge: true parameter.
Example:
db.collection(id).document(uid).set(new HashMap<>() {{
put(pkg, score);
}}, SetOptions.merge())
for the js version
firestore schema:
cars: {
toyota.rav4: $25k
}
js code
const price = '$25k'
const model = 'toyota.rav4'
const field = new firebase.firestore.FieldPath('cars', model)
return await firebase
.firestore()
.collection('teams')
.doc(teamId)
.update(field, price)
Key should not contains periods (.), since it's conflicting with nested fields. An ideal solution is don't make keys are dynamic, those can not be determined. Then you have full control over how the keys should be.

Edit Text Field for Email isn't validating an email address?

why default EditText for email isn't validating an email Address?as EditText field is working for number input.i know that we can validate it by using java.util.regex.Matcher and java.util.regex.Pattern is there any default function as for number is?
inputtype="textEmailAddress" is not working as inputType="number" do work...
Editext field will not validate your email only by setting it's input method to email type.
You need to validate it yourself.
Try this:
Android: are there any good solutions how to validate Editboxes
email validation android
Please use below code for that, it will solve your problem.
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;
}
And see below Stack Overflow link for more information.
Email Validation
You can do any type of validation in android very easily by the oval.jar file. OVal is a pragmatic and extensible general purpose validation framework for any kind of Java objects.
follow this link: http://oval.sourceforge.net/userguide.html
You can downlaod this from here: http://oval.sourceforge.net/userguide.html#download
You can use validation by setting tags in variables
public class Something{
#NotEmpty //not empty validation
#Email //email validation
#SerializedName("emailAddress")
private String emailAddress;
}
private void checkValidation() {
Something forgotpass.setEmailAddress(LoginActivity.this.dialog_email.getText().toString());
Validator validator = new Validator();
//collect the constraint violations
List<ConstraintViolation> violations = validator.validate(forgotpass);
if(violations.size()>0){
for (ConstraintViolation cv : violations){
if(cv.getMessage().contains("emailAddress")){
dialog_email.setError(ValidationMessage.formattedError(cv.getMessage(), forgotpass));
}
}
}
}

Regular Expression not matched

I am trying to validate my string with the regular expression. Here is what I am trying to do
EditText serialText = (EditText) findViewById(R.id.pinText);
serialText.setVisibility(View.VISIBLE);
serialNumber = serialText.getText().toString();
I am storing the serial number in serialNumber
I have the following method to match the regular expression
boolean isRegularSerialNumber(String pinNumber) {
// regular expression to be matched against
String regularString = "[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}";
Pattern pattern = Pattern.compile(regularString);
Matcher matcher = pattern.matcher(pinNumber);
boolean isRegularSerialNumberValid ;
if (pinNumber.matches(regularString))
isRegularSerialNumberValid = true;
else
isRegularSerialNumberValid = false;
return isRegularSerialNumberValid;
}
But I am not able to match this.
Any answer for this? Hope Pattern and Matcher are the right one for this.
What I am trying to do is this, this matched serialNumber I am validating against serial number stored in the database. If match found, it returns success or else failure. And i have entered the exact serial number which is stored in the database but even then it returns failure.
I followed the method what #Stevehb said and i got the match true in that case.
This is how I am sending my data
parameter.add(new BasicNameValuePair("validate", serialNumber));
Breaking my head on this.
The built in String functions should work by themselves. isRegularSerialNumber() could just be
boolean isRegularSerialNumber(String pinNumber) {
String regularString = "[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}";
return pinNumber.matches(regularString);
}
This works for me when I tested 1234-5678-9012-1324 (true) and 12-1234-123-1324 (false).
Also, it looks like you're maybe grabbing the input string from serialText right after you make it visible. Could your problem be in grabbing the text before the user has made any input?
looks much alike .net regex code.
instead of
if (pinNumber.matches(regularString))
try
if (matcher.matches())

Categories

Resources