Reputation: 461
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?
Upvotes: 2
Views: 19135
Reputation: 1
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:
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;
Upvotes: 0
Reputation: 6297
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();
Upvotes: 10