Am creating a form with some Text inputs where a user can update their PIN, so i need the inputs to be only numeric and also kind a password- masked.
I've tried this here but it only makes the input masked and accepts even characters,
TextComponent currentPIN = new TextComponent().labelAndHint("Current Pin").constraint(TextArea.NUMERIC).constraint(TextArea.PASSWORD);
TextComponent newPIN = new TextComponent().labelAndHint("New PIN").constraint(TextArea.NUMERIC).constraint(TextArea.PASSWORD);
TextComponent confirmPIN = new TextComponent().labelAndHint("Confirm PIN").constraint(TextArea.NUMERIC).constraint(TextArea.PASSWORD);
how can I achieve this, I want the input to accept only PIN, that's numeric and be masked.
You cannot chain calls to constraint() that way and have them add up.
From the Javadoc (my emphasis):
public void setConstraint(int constraint)
Sets the constraint which provides a hint to the virtual keyboard input, notice this doesn't limit input type in any way!
Parameters:
constraint - one of ANY, EMAILADDR, NUMERIC, PHONENUMBER, URL, DECIMAL it can be bitwised or'd with one of PASSWORD, UNEDITABLE, SENSITIVE, NON_PREDICTIVE, INITIAL_CAPS_SENTENCE, INITIAL_CAPS_WORD. E.g. ANY | PASSWORD.
The proper form is
...constraint(TextArea.NUMERIC | TextArea.PASSWORD)
Related
I need to write a rule using Drool that will validate that the phone number is valid US number (for the sake of this answer we can use this regex "^([0-9]{3})[0-9]{3}-[0-9]{4}$")
The object structure is like this:
{
"name": {"firstName":"John", "lastName":"Smith"},
"phone": [{"phoneType": "mobile", "phoneNumber":"123456789"}],
"dob":"01/01/2000"
}
Because phone is a list, I don't know how to loop and validate this object. For instance the validation for "dob" field looks something like this:
rule "RuleId: Drool01, Validate dob"
when
$user: user(dob != null)
user(dob not matches "(?:0[1-9]|1[012])" from $user
then
modify($user){setDob(null)};
I appreciate any help on this. I apologize if this is very basic but I literally just started to use Drools.
I'm going to assume these models (irrelevant bits omitted; assume getters and setters):
class User {
private Name name; // Name model not shown, not relevant to this question
private Phone phone;
private String dob;
}
class Phone {
private String phoneType;
private String phoneNumber;
}
We can then write a rule like this:
rule "Invalid Phone Number"
when
$user: User( $phoneNumbers: phone )
exists( Phone( phoneNumber not matches "^([0-9]{3})[0-9]{3}-[0-9]{4}$" ) from $phoneNumbers)
then
// $user has at least 1 phone number which doesn't match the pattern
end
This rule is useful when we only need to know that there exists a bad value. It gets a little more interesting if we actually need to get those bad values (eg. if we want to report out a better error message.)
If we want to trigger the consequences for each bad phone number (eg. if there are 3 phone numbers and 2 are bad, we want to trigger the "then" twice) we could do like this:
rule "Invalid Phone Number - trigger for each"
when
$user: User( $phoneNumbers: phone )
$badPhone: Phone( phoneNumber not matches "^([0-9]{3})[0-9]{3}-[0-9]{4}$") from $phoneNumbers
then
// here $badPhone will be a phone number for $user that doesn't match the pattern
end
You might want to write a rule like this if you want to do something for each bad phone number individually. Consider maybe if we were doing "verified" phone numbers -- for example, they text you passcode that you have to use to verify your phone number; in this case you could text each phone number, one-by-one, to go through this verification process.
Alternatively we could just collect up all of the bad phone numbers and trigger the consequences once for all of those numbers, collectively.
rule "Invalid Phone Number - trigger once for all"
when
$user: User( $phoneNumbers: phone )
$badNumbers: List( size > 0 ) from collect (
Phone( phoneNumber not matches "^([0-9]{3})[0-9]{3}-[0-9]{4}$") from $phoneNumbers
)
then
// $badNumbers is a list of all of the Phone objects that don't match
// the pattern and belong to $user
end
I have a requirement where I need to validate a string:
String input1 = example#gmail.com , example1#gmail.com;
String input2 = example#yahoo.com , example1#gmail.com;
String input 1 == valid ::: Valid because all email ids are of same domain
String input 2 == invalid
You can build the logic in the following way.
String input1 = example#gmail.com , example1#gmail.com , example1#gmail.com;
Follow the steps.
Split the entire string using comma (,). You will get an array of email ids.
From the above array of email id, separate out the domain by stripping from # symbol and put in a HashSet. It means the HashSet should contain all the domains.
If the HashSet size is 1 finally or at the end it means that input1 has same doamins, as per your requirement it is valid.
If the HashSet contains more than 1, as per your requirement it is invalid.
This is a simple logic, However there may be better logic to solve it.
I am new. Trying to do a database retrieve demo to login a system, here is my function code:
I will call goLogin function and pass in the input id and password for validation and I will also get all the id from Database for checking purpose. After ID is correct, only go check the password.
public void goLogin(String id, String pass){
String[99] allID = getAllIDFromDB();
for(int i=0;i<allID.length;i++){
if(allID[i]==id){
String passwordDB = getPasswordFromDB(id);
if(pass==password){
System.out.println("Correct Password");
}else{
System.out.println("Wrong Password");
}
}
}
My peers say I was using too much if else and I can shorten the code and make the program better, and I faced some issue on looping for example when ID and Password are correct, the program will still continue the loop.
Is there any suggestion to make this function better?
First of all, Why retrieve all the user IDs from the database instead make sql query to retrieve the row of this user based on this id.
something like this:
Select * from `users` where id = {id};
And if you want to stop looping a wrong password was found, add break in the else scope.
In my opinion, the main issue of your program is your logic to implement the Login Function.
Login Function implementation can be implemented with various pattern, Based on your program code I will assume you just want a Most Basic Login Function that allow the program to do validation on user input ID and Password.
Actually, this Basic validation can be done in your Database Query. You can just take the user input ID and Password and let Database Query to do filtering and determine if the user input ID and Password is valid or invalid.
First use this Query:
Select DATABASEID From Database Where DATABASEID=inputID and DATABASEPASSWORD=inputPassword;
Java Code:
public void goLogin(String id, String pass){
// Since i changed the Query, you need to pass in the ID and Password to let the Query to filtering
String DatabaseID = getIDFromDB(id, pass);
// Simple Logic, If DatabaseID have value which mean the ID and Password is correct
// Because the Database Query will return null if the ID and Password is Wrong
if(DatabaseID!=null){
System.out.println("ID and Password is Correct.");
}else{
System.out.println("ID or Password is Incorrect.");
}
}
This Logic is very simple, but also come with some drawback, the only Advantage Compare to your code are:
Still able to do basic validation on User Input ID and Password.
Remove for loop and other unnecessary if else.
Only access database for once.
Hope this would help.
Yes, you could even do:
Select * from `users` where id = {id} and password = {password}
Also, to compare Strings in Java, you should use string1.equals(string2), not the == operator.
I'm new in Java, so I don't know very good the language.
I have a simple HTML Form to fill register for Login.
My problem is a detail in the username, it can't have some invalid character (accents and symbols, for example) and I donĀ“t know how to check the username characters.
I used request.getParameter("username") to get username in a String variable.
String username = request.getParameter("username");
How can I proceed?
A simple way is the String#matches(String regex) function:
boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
String username = request.getParameter("username");
boolean valid = (username != null) && username.matches("[A-Za-z0-9_]+");
but if this is to be used multiple times is more efficient to use a Pattern:
Pattern pattern = Pattern.compile("[A-Za-z0-9_]+");
and use it each time:
boolean valid = (username != null) && pattern.matcher(username).matches();
Use this Bean Validation library:
https://github.com/ankurpathak/username-validation
https://mvnrepository.com/artifact/com.github.ankurpathak.username/username-validation
It has all constraints for google like username validation and many more.
Library has different constraint to deal with username validation:
UsernamePattern to allow a-z,0-9,period and underscore characters. These characters can we turned off with some flags in constraints like includePeriod, includeUnderscore and useDigit
EndWithAlphabet to check if username end with alphabet
StartWithAlphabet to check if username start with alphabet
StartWithAlphaNumeric to check username start with alphanumeric
EndWithAlphaNumeric to check username end with alphanumeric
NotContainConsecutivePeriod to check username not contain consecutive period
NotContainConsecutiveUnderscore to check username not contain consecutive underscore
NotContainPeriodFollowedByUnderscore to check username not contain period followed by underscore
NotContainUnderscoreFollowedByPeriod to check username not contain underscore followed by period
All the constraints by default ignore blank so that it will be reposted separately by NotBlank standard bean validation constraint and same can we turned of using ignoreBlank(true by default) flag of each constraint. So google like username can be achieved by:
#UsernamePattern
#StartWithAlphaNumeric
#NotContainConsecutivePeriod
#EndWithAlphaNumeric
#NotBlank
private String username;
I would like to use Android's built-in AccountManager to handle accounts for our native Android app. However, we have a peculiar need.
It appears that Android's concept of an Account is a combination of name (i.e. MazerRackham#example.com) and type (i.e. com.example). Name is the username you login with. Type is associated with your application or company.
However, our REST backend allows a single user to have multiple accounts and each account must be accessed by its own unique hash tied to the combination of one username and one account number (in addition to type).
I already have the AccountAuthenticator, AuthenticationService, and AccountAuthenticatorActivity working for a single user with a single account number and single stored hash. Is there any way in which I could implement my AccountAuthenticator to handle users with multiple accounts under the same username, each requiring a hash? Would it be possible to attach a delimiter to the username and split it into username and account number every time I use it?
If I cannot figure out a way to handle this, how should I gracefully fall back during AbstractAccountAuthenticator.getAuthToken? Would it make sense to set the hash to a special flag value and use legacy login methods for that user? Or is that too much of a hack?
Thanks for your help!
If you don't mind the hash being public, you can certainly make the account name username|hash (or whatever separator you want) - the system does not care what you use for an account name except that it uniquely defines a user.
I ended up serializing the data into the username using an at sign (#) as a delimiter. I chose the at sign because it's the only restricted character in an e-mail address that should only be used exactly one time.
Here is the code from getAuthToken in my AccountAuthenticator which gets called only if I need to obtain a fresh token for that user and account id:
/*
*
* The login params need to handle users with multiple accounts under the same username.
*
* Since Android's AccountManager does not allow multiple accounts per username, I had
* to create a hack which joins and splits the username on a delimiter to serialize the
* data and retrieve the account number for users with multiple accounts. I chose the #
* sign as a delimiter because e-mail addresses have VERY few invalid characters in
* the account name part of the address.
*
* If the user has multiple accounts, we need to create each one in AccountManager.
*
* */
String[] accountParts = account.name.split("#");
numParts = accountParts.length;
if (numParts<2) {
Log.wtf(Config.TAG, "Username split produced too few parts. WTF.");
return null;
}
String email = accountParts[0] + "#" + accountParts[1];
if (numParts==3) {
String account_id = accountParts[2];
} else if (numParts>3) {
Log.wtf(Config.TAG, "Username split produced too many parts. WTF.");
return null;
}