Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Username Validation Java

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?

like image 433
Rodrigo G Rodrigues Avatar asked Apr 08 '26 08:04

Rodrigo G Rodrigues


1 Answers

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();
like image 53
Tobías Avatar answered Apr 10 '26 01:04

Tobías



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!