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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With