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)
Related
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.
I have an activity with text edits one for name, email and password and a button that take the user to next activity.
The problem is that even if the user entered a invalid email address he still can go to second activity, I want the email address to be checked than if he entered a valid email address he can go to second activity, if not a toast message appears says INVALID EMAIL ADDRESS.
I am working with KOTLIN but I can work also with java.
Please can anyone guide me on how I can do it ?
Thanks in advance.
There is an interesting Java Library that you can use to test if an E-mail is valid or not.
Here is the Gradle dependency:
implementation group: 'commons-validator', name: 'commons-validator', version: '1.6'
Here is how you would validate an e-mail string:
First, capture the value of the editText into a String object.
Then you can use the following pattern to capture a Boolean value that tells if the user has entered a Valid E-mail address.
String email = "user#domain.com";
Now, you can use the E-mail Validator:
boolean isValid = EmailValidator.getInstance().isValid(email);
This is the easiest way I found.
I hope that helps!
fun isEmailValid(email: String): Boolean {
return Pattern.compile(
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]|[\\w-]{2,}))#"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9]))|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$"
).matcher(email).matches()
}
We have simple Email pattern matcher now
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
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.
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.
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())